AngularJS watch not working for drop-down(select) change

2.2k Views Asked by At

AngularJS watch not working for drop-down change. Here is my code, this is not exactly the original code , I just simulated.

Code :

<body ng-app="app" ng-controller="ctrl">
<select ng-model=“selectedId" ng-options="val as val.name for val in options | orderBy:'id'">
</select>
<script>
angular.module("app",[])
  .controller("ctrl",['$scope',function($scope){
    $scope.options = [
      {"id":1, "name":"First"},
      {"id":2, "name":"Second"}
    ]
    $scope.selectedId = {"id":1, "name":"First"}
    $scope.$watch('selectedId’,function(selVal) {
       console.log(selVal);
     });
  }])
 </script>
</body>
3

There are 3 best solutions below

0
SANN3 On BEST ANSWER

I am adding the working solution.

I have changed $scope.selectedId to $scope.filters.selectedId and add a watch on $scope.filters.selectedId.

I don't know why this works.

1
Jenny On

You have so many Typo try to set $scope.options[0] instead of options[0]

angular.module("app",[])
  .controller("ctrl",['$scope',function($scope){
    $scope.options = [
      {id:1, name:'First'},
      {id:2, name:'Second'}
    ]
    $scope.selectedId = $scope.options[0];
    $scope.$watch('selectedId',function(selVal) {
       console.log(selVal);
     });
  }])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<body ng-app="app" ng-controller="ctrl">
<select ng-model="selectedId" ng-options="val as val.name for val in options">
</select>
</body>
<html>

0
Sai On

Special characters are used in the code instead of normal quotes and use $scope.options[0] instead of options[0].

Working plunker here