嘿,我是js Angular的新手,无法弄清楚我做错了什么,如何在ng-click函数中放置一个对象方法:
<div class="container" ng-repeat="exercise in exercises">
<div class="row">
<div class="exercise-icon col-xs-2">
<img ng-src="{{ exercise.icon }}">
</div>
<div class="col-xs-6">
<p class="exercise-name"> {{ exercise.name }} </p>
</div>
<div class="col-xs-4 counters">
<span class="decrease">-</span><span class="count"> {{ exercise.count }} </span>
<span class="increase" ng-click="{{exercise.increase($index)}}">+</span>
</div>
</div>
这是控制器脚本:
app.controller('MainController', ['$scope', function($scope) {
$scope.exercises = [
{
icon: 'img/pushup.jpg',
name: 'Pushups',
count: 20
},
{
icon: 'img/squat.jpg',
name: 'Squats',
count: 15
},
{
icon: 'img/pullup.jpg',
name: 'Pullups',
count: 10
},
{
icon: 'img/row.jpg',
name: 'Rows',
count: 10
},
{
icon: 'img/lunge.jpg',
name: 'Lunges',
count: 10
},
{
icon: 'img/stepup.jpg',
name: 'Step Ups',
count: 10
},
{
icon: 'img/situp.jpg',
name: 'Sit Ups',
count: 15
}
];
$scope.increase = function($index) {
$index.count++;
};
}]);
练习图标,名称和计数都显示但是单击功能由于某种原因不起作用,将对象方法插入到ng-click中的语法是否正确?我无法在线找到任何适用的答案。 我期望的功能是每次按下时都会增加。
答案 0 :(得分:5)
这里有两点错误,你错误地调用了你的函数:
{{exercise.increase($index)}}
应该是
increase($index)
并且您将$index
视为对象,它应该是这样的:
$scope.increase = function($index) {
$scope.exercises[$index].count++;
};
答案 1 :(得分:1)
变化:
<span class="increase" ng-click="{{exercise.increase($index)}}">+</span>
为:
<span class="increase" ng-click="exercise.increase($index)">+</span>
Angular中不需要括号。
答案 2 :(得分:1)
您可以在不调用函数的情况下实现结果,并在ng-click
本身内部执行操作。
<span class="increase" ng-click="exercises.count =exercises.count+1 ">+</span>
答案 3 :(得分:0)
尝试这个
<span class="increase" ng-click="increase($index)">+</span>
和你的控制者
$index = $index + 1;