步骤-1-Todo值将增加对应待办事项的每次点击
<li class="list-group-item" ng-repeat="todo in todos">
<span ng-click="count = count + 1" ng-init="count=0"> value= {{count}} </span>
</li>
步骤2 - 我如何计算&#39;&#39;和todo&#39; id&#39;每次点击进入我的功能
问题(此处有问题)
我的代码(我知道错了)
<li class="list-group-item" ng-repeat="todo in todos">
<span ng-click="addLike(todo._id) (count = count + 1)" ng-init="count=0"> value= {{count}} </span>
</li>
function TodoCtrl($scope) {
$scope.todos = [
{text:'todo one'},
{text:'todo two', done:false}
]
};
答案 0 :(得分:2)
ng-click="count=count+1; addLike(todo._id, count)"
<强> Fiddle 强>
Bhesh Gurung向a resource提供了有关为什么增量运算符(++
)不适合我们的一些见解:
由于++ points不是有效的Angular表达式,会发生什么?控制台中的有用错误消息指出了我们正确的方向:
错误:[$ parse:syntax]语法错误:令牌'+'不是表达式[++ points]第2列的主表达式,从[+ points]开始
从这条消息中,我们看到我们的表达式使用了一些不受支持的语法(在本例中,是预增量运算符++)。错误消息是由非常神奇的核心Angular服务$ parse引发的。
值得注意的是,每个按钮都有自己的范围,因此计数会独立增加。
答案 1 :(得分:2)
在这里如何做到这一点
只需增加addLike
功能
<li class="list-group-item" ng-repeat="todo in todos">
<span ng-click="addLike(todo._id,this)"> value= {{todo.count}} </span>
</li>
function TodoCtrl($scope) {
$scope.todos = [{
text: 'todo one'
}, {
text: 'todo two',
done: false
}]
$scope.addLike = function(todoid, obj) {
if (obj.todo.count == undefined) {
obj.todo.count = 1;
} else {
obj.todo.count++;
}
}
};
答案 2 :(得分:2)
主要思想是将对象传递给处理程序并对其进行修改。
var myApp = angular.module('myApp', []);
function TodoCtrl($scope) {
$scope.todos = [{
text: 'todo one'
}, {
text: 'todo two',
done: false
}];
$scope.likeIt = function likeIt(model) {
model.count = model.count + 1 || 1;
}
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<ul ng-controller="TodoCtrl">
<li class="list-group-item" ng-repeat="todo in todos">{{todo.text}}
<button class="btn btn-default" ng-click="likeIt(todo)">value- {{todo.count || 0}}</button>
</li>
</ul>
</div>
&#13;
答案 3 :(得分:1)
如果您想要保留计数数据,最好委托给工厂:
HTML
<div ng-app="myApp">
<ul ng-controller="TodoCtrl">
<li class="list-group-item" ng-repeat="todo in todos">
{{todo.text}}
<button class="btn btn-default" ng-click="count(todo)"> value- {{todo.count}} </button>
</li>
</ul>
</div>
JS
var myApp = angular.module('myApp', []);
myApp.factory('todosFact', function(){
var todos = [
{text:'todo one', count: 0},
{text:'todo two', done:false, count: 0}
]
return todos
})
myApp.controller('TodoCtrl', function(todosFact, $scope){
$scope.todos = todosFact;
$scope.count = function count(todo){
todo.count++;
return;
}
})
我使用$ scope,但您也可以使用controllerAs语法,这是推荐的方法(http://toddmotto.com/digging-into-angulars-controller-as-syntax/)