Change a value inside ng-repeat cycle with ng-click

 ̄綄美尐妖づ 提交于 2019-12-10 16:18:58

问题


I want to change a value of an item inside an ng-repeat cycle using a function.

This for example won't work.

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

Full example

http://plnkr.co/edit/kobMJCsj4bvk02sveGdG


回答1:


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>

Demo Here

Extended

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


来源:https://stackoverflow.com/questions/35650518/change-a-value-inside-ng-repeat-cycle-with-ng-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!