angularjs – 在’view’中使用ng-init的替代方法?
发布时间:2020-12-17 08:51:51 所属栏目:安全 来源:网络整理
导读:我正在尝试为我的应用创建一个“喜欢”的功能.我希望能够将动态生成的数字的值设置为“like count”.问题在于使用’ng-init’,因为文档说这是一个不好的方法! 如何在“控制器”中设置值而不是“视图”? 这是我到目前为止: !doctype htmlhtml ng-app="plun
我正在尝试为我的应用创建一个“喜欢”的功能.我希望能够将动态生成的数字的值设置为“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; }; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |