Liam Collins Liam Collins - 1 month ago 5
AngularJS Question

Pass object key in ng-change

Is there a way to pass an object key or value with ng-change in a multi select element where ng-options is an object?

In below example, the

$scope.check
function doesn't receive any paramter, but would like it to get either the key or value.

<select ng-model="$scope.someArray" ng-change="$scope.check(key)" ng-options="key as val for (val, key) in $scope.options" multiple></select>


where
$scope.options = {a: 1, b: 2}

Answer

Change your select, You should not use $scope in view, also use a variable for the ng-model and pass it inside the check() function

HTML:

 <div class="media-list" ng-controller="dishDetailController">
   <select ng-model="selected"  ng-change="check(selected)" ng-options="key as val for (val, key) in options"></select>
  </div>

Controller:

app.controller("dishDetailController", ["$scope",
  function($scope) {
   $scope.selected ;
   $scope.options = {a: 1, b: 2};
   $scope.check = function(val){
    alert(val); 
   }
  }
]);

DEMO