【问题标题】:Change a value inside ng-repeat cycle with ng-click使用 ng-click 更改 ng-repeat 循环内的值
【发布时间】:2016-06-09 14:20:50
【问题描述】:

我想使用函数在 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';
};

完整示例

http://plnkr.co/edit/kobMJCsj4bvk02sveGdG

【问题讨论】:

    标签: javascript angularjs angularjs-controller angularjs-controlleras


    【解决方案1】:

    当使用controllerAs 模式时,您应该在从控制器函数访问任何变量时使用controller 别名。但这应该限制在controller 的this 上下文中。

    <button ng-click="todoList.example(todo)">Click me</button>
    

    Demo Here

    扩展

    在控制器工厂函数中使用 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';
        };
      });
    

    【讨论】:

      猜你喜欢
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多