我正在尝试为我的应用创建一个"喜欢"的功能.我希望能够将动态生成的数字的值设置为"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>
Run Code Online (Sandbox Code Playgroud)
谢谢,
J.P
只是改变
`<span ng-init="likeCount=feed.likes.length">{{likeCount}}</span>`
Run Code Online (Sandbox Code Playgroud)
每
`<span>{{feed.likes.length}}</span>`.
Run Code Online (Sandbox Code Playgroud)
如果您由于其他原因仍然需要控制器中的计数(我看不到),请创建一个控制器,让我们假设FeedCtrl,并将其添加到您的article:
<article ng-repeat="feed in feeds" ng-controller="FeedCtrl">
...
<span>{{likeCount}}</span>
</article>
Run Code Online (Sandbox Code Playgroud)
你的 FeedCtrl 将是:
function FeedCtrl($scope) {
$scope.$watch('feed.likes.length', function(newValue) {
$scope.likeCount = newValue;
});
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是创建一个函数来解析该值:
<article ng-repeat="feed in feeds" ng-controller="FeedCtrl">
...
<span>{{likeCount()}}</span>
</article>
Run Code Online (Sandbox Code Playgroud)
function FeedCtrl($scope) {
$scope.likeCount = function() {
return $feed && $feed.likes ? $feed.likes.length : undefined;
};
}
Run Code Online (Sandbox Code Playgroud)