如何在角度控制器或范围上使用 angular.toJson [英] How to use angular.toJson on a angular controller or scope

查看:19
本文介绍了如何在角度控制器或范围上使用 angular.toJson的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅我下面的 jsFiddle 示例,其中我尝试使用 angular.toJson 将 Angular.js 对象推送到 JSon 表示中.结果我得到的只是$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' }

是否有更好的方法以 JSon 形式获取该数据(即不使用范围)?显然我可以手动滚动一个方法来获取值并推出一个 JSon 表示,但是随着控制器的变化,该函数也会发生变化,所以我宁愿只调用一个 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: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" />

然后在您的控制器中:

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

事实上,使用 angular.js 过滤器可以更容易地做到这一点,请检查这个 jsFiddle:http://jsfiddle.net/pkozlowski_opensource/ASspB/2/ 有:

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}}

使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆