1

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

This for example won't work.

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

Full example

http://plnkr.co/edit/kobMJCsj4bvk02sveGdG

Claudio Ɯǝıs Mulas
  • 1,116
  • 3
  • 15
  • 24
  • I think i had already told you to keep `this` in some variable and then used it in [this answer](http://stackoverflow.com/a/35650598/2435473) – Pankaj Parkar Feb 26 '16 at 11:57

2 Answers2

0

Inside a function your this will point to something else, not your original controller this, you can solve it by doing the following.

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

Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
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
    };
  });