如何使用angular.toJson一个角控制器或范围上 [英] How to use angular.toJson on a angular controller or scope
问题描述
请看到我的努力推动一个Angular.js对象为使用angular.toJson一个JSON重新presentations我下面的jsfiddle例子。我所得到的只是$范围作为结果。
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.
我想要做的就是当前的属性和值。在这个例子中我会希望看到的是
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' }
有没有更好的方式来获得在JSON形式的数据(即不使用范围)?很显然,我可以手卷,是以价值观,推动了JSON再presentation但作为控制器的变化也是如此会的功能,所以我宁愿只是调用的toJSON型方法的方法。任何人都知道的正确的方式做到这一点?先谢谢了。
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.
推荐答案
我可以看到你是从jQuery的未来世界,但angular.js事情变得简单多了,请检查该的jsfiddle:<一href=\"http://jsfiddle.net/pkozlowski_opensource/ASspB/1/\">http://jsfiddle.net/pkozlowski_opensource/ASspB/1/
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/
使用您可以将事件angular.js得多,简单得多:
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);
}
其实可以这样做更容易与angular.js过滤器,检查此的jsfiddle:<一href=\"http://jsfiddle.net/pkozlowski_opensource/ASspB/2/\">http://jsfiddle.net/pkozlowski_opensource/ASspB/2/其中有:
{{user | json}}
使用angular.js你需要忘却了一下一些jQuery的习惯,但这是好的,因为事情变得非常非常容易的大部分时间。
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.
这篇关于如何使用angular.toJson一个角控制器或范围上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!