How to use angular.toJson on a angular controller or scope

前端 未结 3 1740
有刺的猬
有刺的猬 2020-12-13 19:53

Please see my following jsFiddle example where I am trying to push an Angular.js object into a JSon representations using angular.toJson. What I get is just \"$SCOPE\" as th

3条回答
  •  甜味超标
    2020-12-13 20:25

    Since you asked how to get this without the $scope, here is an angular 1.5.9 example with components (they were introduced in angular 1.5.8).

    This would allow you to migrate easier to angular 2, too. And of course you would separate all this sources into separate files.

    You should give TypeScript a try. This would get you Type Safety and a lot of sugar syntax and a easier way to programming in an oriented way. Also you could see where a method is defined and what methods and properties it has.

    var module = angular.module("settingsApp", []);
    
    module.service("userSettingsService", UserSettingsService);
    
    module.component("userDetails", {
            template: `
            	
                
                
                
    {{$ctrl.json}}`, controller: UserDetailsController }); UserSettingsService.$inject = ["$q"]; function UserSettingsService($q) { var _this = this; this.$q = $q; this.userDetails = [{ firstName: "Frank", lastName: "Williams" }]; this.getSettings = function (id) { return _this.$q.resolve(this.userDetails[id]); } } UserDetailsController.$inject = ["userSettingsService"]; function UserDetailsController(userSettingsService) { var _this = this; var userId = 0; this.userSettingsService = userSettingsService; userSettingsService.getSettings(userId).then(function (data) { _this.userDetail = data; }); } UserDetailsController.prototype.showJson = function() { this.json = angular.toJson(this.userDetail); } angular.bootstrap(document, ['settingsApp']);
    
    
    

提交回复
热议问题