Search code examples
javascriptangularjsng-options

Issue on ngOptions track by


I have some issue with AngularJs option/selector which I uses ngOptions to create. The problem I have is that it doesn't trigger the method I have in ngChange. I found out that's because in actionList the name property isn't unique. So if I change so they are unique it will works as intended. However I want them to be named like how it is now.

So I guess I could try something like ng-options="action.name for action in ctrl.actionList track by action.value". But it doesn't work. Anyone who can help me out here?

HTML

<select id="someOptions" class="dropdown dropdown-md"
    ng-model="ctrl.settingAction"
    ng-change="ctrl.onChangeAction()"
    ng-options="action.name for action in ctrl.actionList">
</select>

Data structure

actionList = [{
    name: "Running Man"
    value: "RUN"
}, {
    name: "Running Man"
    value: "JUMP"
}]

JS

public onChangeAction(): void {
    console.log(this.settingAction);
}

Solution

  • DEMO

    angular.module('myApp',[]).controller('myCtrl', function($scope){
     var ctrl = this;
     this.actionList =[{
        "name": "Running Man",
        "value": "RUN"
    }, {
        "name": "Running Man",
        "value": "JUMP"
    }];
    
    this.onChangeAction = function(){
     alert(this.settingAction.value);
    }
     
              
     });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="myCtrl as ctrl">
     <select id="someOptions" class="dropdown dropdown-md"
        ng-model="ctrl.settingAction"
        ng-change="ctrl.onChangeAction()"
        ng-options="action.name for action in ctrl.actionList">
    </select>
    </div>