使用ng-click在ng-repeat循环内更改一个值
使用ng-click在ng-repeat循环内更改一个值
我想要通过一个函数来改变ng-repeat循环中的一个项目的值。\n例如,下面的代码是行不通的。\nHTML\n
- {{todo.name}}
\nJS\n
$scope.example = function(v) { v.name = '我现在不同了'; };
当使用controllerAs
模式时,应该在访问来自控制器函数的任何变量时使用controller
别名。但是,它应该绑定到controller
的this
上下文。
在上面的代码中,当点击按钮时,调用了todoList.example(todo)
方法。该方法会改变todo
对象的name
属性为'ora bene'。
问题的出现是因为在控制器函数中,没有正确地使用this
关键字。解决方法是在控制器函数中,将this
赋值给某个变量(例如toList
),以确保所使用的this
是正确的this
。
以下是修复后的代码:
angular.module('todoApp', []) .controller('TodoListController', function() { var toList = this; toList.todos = [{name:'test 1'},{name:'test 2'}]; toList.example = function(v) { v.name = 'ora bene'; }; });
通过以上修改,问题得到解决。