Ng-click doesn't work inside ng-repeat

后端 未结 8 971
悲哀的现实
悲哀的现实 2020-11-27 18:42

Ng-click doesn\'t work from inside ng-repeat. Outside it works. I\'ve put a fiddle here


                      
相关标签:
8条回答
  • 2020-11-27 19:13

    Use controllers with the 'as' keyword.

    Check the documentation on angularjs on controllers.

    For the above question:

    <div ng-controller="MyCtrl as myCntrl">
     <a ng-click="myCntrl.triggerTitle='This works!'">test</a>
        <h5>Please select trigger event: [{{myCntrl.triggerEvent}}] {{myCntrl.triggerTitle}}</h5>
           <ul class="dropdown-menu">
             <li ng-repeat="e in myCntrl.events">
                 <a ng-click="myCntrl.triggerTitle=e.name; myCntrl.triggerEvent = e.action;">{{e.action}} - {{e.name}}</a>
             </li>
           </ul>
    </div>
    

    This will attach the properties and functions to the scope of the controller.

    0 讨论(0)
  • 2020-11-27 19:16

    Because ng-repeat creates a new scope.

    This has been answered numerous time, because the nuance is a bit difficult to understand, especially if you don't know everything about js's prototypal inheritance : https://github.com/angular/angular.js/wiki/Understanding-Scopes

    EDIT: it seems this answer is very controversial. Just to be clear – this is how JS works. You really shouldn't try to learn Angular before understand how JS works. However, the link does seem to miss

    So, here's an example on how JS works in this case:

    var a = {value: 5};
    var b = Object.create(a); // create an object that has `a` as its prototype
    
    // we can access `value` through JS' the prototype chain
    alert(b.value); // prints 5
    // however, we can't *change* that value, because assignment is always on the designated object
    b.value = 10;
    alert(b.value); // this will print 10...
    alert(a.value); // ... but this will print 5!
    

    So, how can we work around that?

    Well, we can "force" ourselves to go through the inheritance chain – and thus we'll be sure we're always accessing the correct object, whether accessing value or modifying it.

    var a = {obj: {value: 5}};
    var b = Object.create(a); // create an object that has `a` as its prototype
    
    // we can access `value` through JS' the prototype chain:
    alert(b.obj.value); // prints 5
    // and if we need to change it,
    // we'll just go through the prototype chain again:
    b.obj.value = 10;
    // and actually refer to the same object!
    
    alert(b.obj.value == a.obj.value); // this will print true
    
    0 讨论(0)
提交回复
热议问题