Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

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

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 the result.

http://jsfiddle.net/K2GsS/12/

What I want to do is get the current properties and values. In this example what I would hope to see is

{ firstName: 'Frank', lastName: 'Williams' }

Is there a better way to get at that data in JSon form (ie not using scope)? Obviously I could hand roll a method that takes the values and pushes out a JSon representation but as the controller changes so too would that function so I would rather just call a toJson type method. Anyone know of the proper way to do this? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I can see that you are coming from the jQuery world, but with angular.js things are getting much simpler, please check this jsFiddle: http://jsfiddle.net/pkozlowski_opensource/ASspB/1/

With angular.js you can attach events much, much simpler:

 <input type="button" ng-click="showJson()" value="Object To JSON" />

and then in your controller:

 $scope.showJson = function() {
    $scope.json = angular.toJson($scope.user);
}

In fact this could be done even easier with angular.js filters, check this jsFiddle: http://jsfiddle.net/pkozlowski_opensource/ASspB/2/ which has:

{{user | json}}

With angular.js you need to "unlearn" a bit some of the jQuery habits, but this is good since things get much, much easier most of the time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...