我正在尝试为我的应用创建一个“喜欢”的功能.我希望能够将动态生成的数字的值设置为“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
只是改变
原文链接:https://www.f2er.com/angularjs/141095.html`<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; }; }