我正在尝试为我的应用程序创建一个“喜欢”功能。我希望能够将动态生成的数字的值设置为“喜欢计数”。问题出在使用“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>
Thanks,
JP
只是改变
`<span ng-init="likeCount=feed.likes.length">{{likeCount}}</span>`
per
`<span>{{feed.likes.length}}</span>`.
如果由于其他原因您仍然需要控制器中的计数(我看不到),请创建一个控制器,让我们假设FeedCtrl
,并将其添加到您的article
:
<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;
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)