Dean Christian Armada Dean Christian Armada - 7 months ago 999
Javascript Question

AngularJS trigger ng-change not working

I just want to simply trigger a change whenever I click a button. The change will just alert a text. However the trigger does not work please help.

Here is the code:

<!DOCTYPE html>
<html ng-app="myApp">

<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>

<body ng-controller="myCtrl">
<input type="text" ng-model="first.name"> <br />
<input type="checkbox" ng-model="same" id="sames" ng-change="sameAsAbove(first, second)"> Same as above <br />
<select ng-model="change" id="changes" ng-change="changeOver()">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="text" ng-model="second.name">
<input type="text" ng-model="second.school">
<span ng-click="clickMe()">Click Me!</span>
<!-- <span id="clickMe">Click Me!</span> -->
{{ same }}
<script type="text/javascript">
app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.sameAsAbove = function(primary, receiver){
receiver['name'] = primary['name'];
};
$scope.clickMe = function(){
angular.element(document.getElementById('changes')).triggerHandler('change');
// x = angular.element(document.getElementById('changes')).val();
// alert(x);
}
$scope.changeOver = function(){
alert("deam");
}
});
$("#clickMe").click(function(){
// alert("czxvzx");
// $("#same").trigger("click");
$("#changes").change();
});
</script>
</body>
</html>


Here is the link to plunker:
http://plnkr.co/edit/zErS4DaTgR79SBLbtGOy?p=preview

Answer

Try this

 <script type="text/javascript">
      app = angular.module('myApp', []);
      app.controller('myCtrl', function($scope,$timeout){
        $scope.sameAsAbove = function(primary, receiver){
          receiver['name'] = primary['name'];
        };
        $scope.clickMe = function(){
         $timeout(function() {
                      angular.element(document.getElementById('changes')).triggerHandler('change');
  }, 100);

         // x = angular.element(document.getElementById('changes')).val();
         // alert(x);
        }
        $scope.changeOver = function(){
          alert("deam");
        }
      });
      $("#clickMe").click(function(){
        // alert("czxvzx");
        // $("#same").trigger("click");
        $("#changes").change();
      });
    </script>

By adding $timeout your problem get resolved.