我正在尝试为我的应用创建一个“喜欢”的功能.我希望能够将动态生成的数字的值设置为“like count”.问题在于使用’ng-init’,因为文档说这是一个不好的方法!
如何在“控制器”中设置值而不是“视图”?
这是我到目前为止:
<!doctype html> <html ng-app="plunker" > <head> <Meta charset="utf-8"> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"> <article ng-repeat="Feed in Feeds"> <h3>{{Feed.createdby}}</h3> <p>{{Feed.content}}</p> <button ng-click="likeClicked($index)">{{isLiked[$index]|liked}}</button> <span ng-init="likeCount=Feed.likes.length">{{likeCount}}</span> </article> </body> </html>
谢谢,
J.P
只是改变
`<span ng-init="likeCount=Feed.likes.length">{{likeCount}}</span>`
每
`<span>{{Feed.likes.length}}</span>`.
如果由于某些其他原因(我看不到)仍然需要控制器中的计数,请创建一个控制器,让我们假设FeedCtrl,并将其添加到您的文章中:
<article ng-repeat="Feed in Feeds" ng-controller="FeedCtrl"> ... <span>{{likeCount}}</span> </article>
你的FeedCtrl将是:
function FeedCtrl($scope) { $scope.$watch('Feed.likes.length',function(newValue) { $scope.likeCount = newValue; }); }
<article ng-repeat="Feed in Feeds" ng-controller="FeedCtrl"> ... <span>{{likeCount()}}</span> </article>
function FeedCtrl($scope) { $scope.likeCount = function() { return $Feed && $Feed.likes ? $Feed.likes.length : undefined; }; }
原文地址:https://www.jb51.cc/angularjs/141095.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。