使用ng-click在ng-repeat循环内更改一个值

19 浏览
0 Comments

使用ng-click在ng-repeat循环内更改一个值

我想要通过一个函数来改变ng-repeat循环中的一个项目的值。\n例如,下面的代码是行不通的。\nHTML\n

  • {{todo.name}}

\nJS\n

$scope.example = function(v) {
  v.name = '我现在不同了';
};

\n完整示例\nhttp://plnkr.co/edit/kobMJCsj4bvk02sveGdG

0
0 Comments

当使用controllerAs模式时,应该在访问来自控制器函数的任何变量时使用controller别名。但是,它应该绑定到controllerthis上下文。

在上面的代码中,当点击按钮时,调用了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';
    };
  });

通过以上修改,问题得到解决。

0