使用对话框更改ng-repeat循环内的值

时间:2016-02-26 11:42:08

标签: javascript angularjs

我想使用对话框然后使用函数更改ng-repeat循环中项目的值。

例如,这不起作用。

HTML

  <div ng-controller="TodoListController as todoList">
    <ul class="unstyled">
      <li ng-repeat="todo in todoList.todos">
        <label class="checkbox">
          <span>{{todo.name}}</span>
          <button ng-click="todoList.example(todo)">Click me</button>
        </label>
      </li>
    </ul>
    <div ng-if="todoList.show_box">
      <button ng-click="todoList.change_me()">Now change me</button>
    </div>
  </div>

JS

angular.module('todoApp', [])
  .controller('TodoListController', function() {
    this.todos = [{
      name: 'test 1'
    }, {
      name: 'test 2'
    }];

    this.example = function(v) {
      this.tmp = v;
      this.show_box = true;
    };

    this.change_me = function(v) {
       this.tmp.v.name = 'now it\'s ok';
    };
  });

完整示例

http://plnkr.co/edit/kobMJCsj4bvk02sveGdG

2 个答案:

答案 0 :(得分:0)

在函数内部,this将指向其他内容,而不是原始控制器this,您可以通过执行以下操作来解决此问题。

var self = this;

self.todos = [{
  name: 'test 1'
}, {
  name: 'test 2'
}];

self.example = function(v) {
  self.tmp = v;
  self.show_box = true;
};

self.change_me = function(v) {
   self.tmp.v.name = 'now it\'s ok';
};

more info about this

答案 1 :(得分:0)

angular.module('todoApp', [])
  .controller('TodoListController', function() {
    this.todos = [{
      name: 'test 1'
    }, {
      name: 'test 2'
    }];

    this.example = function(v) {
      this.tmp = v;
      this.show_box = true;
    };

    this.change_me = function(v) {
       this.tmp.name = 'now it\'s ok'; //this.tmp.v.name will give u undefined
    };
  });