我想在 ng-repeat 循环中使用函数更改项目的值。
例如,这是行不通的。
HTML
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<span>{{todo.name}}</span>
<button ng-click="example(todo)">Change me</button>
</li>
</ul>
JS
$scope.example = function(v) {
v.name = 'i am different now';
};
完整示例
最佳答案
当使用 controllerAs
模式时,您应该在从 Controller 函数访问任何变量时使用 controller
别名。但这应该绑定(bind)到 controller
的 this
上下文。
<button ng-click="todoList.example(todo)">Click me</button>
扩展
在 Controller 工厂函数中使用 this
关键字时还要记住。您应该将 this
变量分配给某个变量,以确保您正在使用的 this
不是其他 this
,请查看 this
context related issue .
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';
};
});
关于javascript - 使用 ng-click 更改 ng-repeat 循环中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35650518/