Jakub Kolčář
Jakub Kolčář

Reputation: 304

Firing change event on model change

I need to trigger the 'change' javascript event on those all SELECT elements where model value changes. The values of model are changed programatically through scope, so using ngChange is out of the play (reacts only on user-made value changes).

Any help please?

Code example: PLNKR

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'oldname';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <select ng-model="name" class="myInput" onChange="alert('changed');" >
        <option value="oldname">oldname</option>
        <option value="newname">newname</option>
    </select>
    <button ng-click="name='newname'">Change by Anguar</button>
  </div>
  </div>

Selecting select options shows alert. When I click the button, value (model) does get changed but alert is not shown because mode change doesn't trigger 'change' event.

Upvotes: 1

Views: 1970

Answers (2)

Kaushal Niraula
Kaushal Niraula

Reputation: 576

you can use $scope.$watch to watch for changes in the model and trigger change event

$scope.$watch('name', function(){
    //slct is the id for the select
    $('#slct').trigger('change');
  })

see plnkr

Upvotes: 1

Dacheng
Dacheng

Reputation: 156

onChange is a javascript event handler not tied to angular's digest loop. Try using ng-change instead.

Upvotes: 0

Related Questions