使用 ng-click 更改 ng-repeat 循环内的值 [英] Change a value inside ng-repeat cycle with ng-click
问题描述
我想使用函数更改 ng-repeat 循环内项目的值.
I want to change a value of an item inside an ng-repeat cycle using a function.
例如这行不通.
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';
};
完整示例
http://plnkr.co/edit/kobMJCsj4bvk02sveGdG
推荐答案
当使用 controllerAs
模式时,你应该使用 controller
别名,同时从控制器函数访问任何变量.但这应该绑定到 controller
的 this
上下文.
When using controllerAs
pattern, you should be using controller
alias while accessing any variable from controller function. But that should be bounded to this
context of controller
.
<button ng-click="todoList.example(todo)">Click me</button>
扩展
在控制器工厂函数中使用 this
关键字时也要记住.您应该将 this
变量分配给某个变量,以确保您使用的 this
不是其他 this
,请查看 this
上下文相关问题.
Also keep in mind while using this
keyword inside a controller factory function. You should assign this
variable to some variable to ensure that this
which you are using is not other this
, look at 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';
};
});
这篇关于使用 ng-click 更改 ng-repeat 循环内的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!