2016-02-26 33 views
1

我想要使用對話框然後使用函數更改ng-repeat循環內的項目值。使用對話框更改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

+0

我想我已經告訴你保持'this'一些變量,然後用它在[這個答案](http://stackoverflow.com/a/35650598/2435473) –

回答

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

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