使用 ng-click 更改 ng-repeat 循环内的值

问题描述:

我想使用函数更改 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 别名,同时从控制器函数访问任何变量.但这应该绑定到 controllerthis 上下文.

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';
    };
  });