3

If I have....

<ul>
   <li ng-repeat="s in collection">
     <select ng-change="update()">
        <option></option>
     </select>
   </li>
</ul>

How do I get a reference to the specific select that raises a call to update()?

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189
  • possible duplicate of [How to get the DOM element that triggered ng-change?](http://stackoverflow.com/questions/17007986/how-to-get-the-dom-element-that-triggered-ng-change) – Giorgi Jul 15 '13 at 14:22

1 Answers1

10

Like this & heres the fiddle:

<div ng-controller="MyCtrl">
  <ul>
   <li ng-repeat="s in collection">
     Hello I am {{s.name}} & these are my options
     <select ng-options="o as o for o in s.options" ng-model="s.selectedOption" ng-change="optionChanged()">
     </select>
   </li>
</ul>
</div>

<script>
var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.collection = [
        {'name':'one', 'value':1, 'options':['A','B']},
        {'name':'two', 'value':2, 'options':['C','D']}
    ];

    $scope.optionChanged = function(){
        console.debug(this.s.selectedOption);
    }
}
</script>
marko
  • 2,841
  • 31
  • 37
  • Yeah cool, thanks. But where does 'this' come from? I thought it was $scope all the way. – Ian Warburton Jul 15 '13 at 14:44
  • 2
    Good question. I bumped into this when I was struggling with ng-repeat. There's been some debate over this here http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers, and it seems since this is a ng-repeat-directive it will create child scopes where I can access its model, since that's "the context from where the method is invoked". I feel that a more "straight to the metal"-answer requires some research on the source code of ng-repeat. – marko Jul 15 '13 at 15:01
  • Is there a better way of accessing the index of the item other than this... ng-model="s.selectedOption($index)"? – Ian Warburton Jul 15 '13 at 15:16