Dean Christian Armada
Dean Christian Armada

Reputation: 7364

AngularJS select change trigger

I am trying to do a script that will copy the value of one select tag model to another and then trigger its ng-change function using a checkbox. What happens is when you click the checkbox, it does copy the value but the trigger does not work anymore. Seems like there is a conflict between setting a model's value and doing the trigger because either one of them fails.

Here is my 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">
    <select ng-model="first.selection" id="first" ng-change="changeOver('dean')">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select> <br />
    <input type="checkbox" ng-model="same" id="same" ng-change="sameAsAbove(first, second)"> Same as above <br />
    <select ng-model="second.selection" id="second" ng-change="changeOver('armada')">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>
    <!-- <span id="clickMe">Click Me!</span> -->
    <script type="text/javascript">
      app = angular.module('myApp', []);
      app.controller('myCtrl', function($scope, $timeout){
        $scope.first = {};
        $scope.second = {};
        $scope.sameAsAbove = function(primary, receiver){
            receiver['selection'] = primary['selection'];
            $timeout(function() {
                 angular.element(document.getElementById('second')).triggerHandler('change');
            }, 100);
        };
        $scope.changeOver = function(value){
          alert(value);
        }
      });
      $("#clickMe").click(function(){
        // alert("czxvzx");
        // $("#same").trigger("click");
        $("#changes").change();
      });
    </script>
  </body>
</html>

Here is the plunkr url: http://plnkr.co/edit/zErS4DaTgR79SBLbtGOy?p=preview

Upvotes: 1

Views: 2092

Answers (1)

DK3
DK3

Reputation: 403

In DOM body you should change this line like this.

<select ng-model="second.selection" id="second" ng-change="same=second.selection">

and use watch to change the checkbox value

$scope.$watch("same", function(newValue, oldValue){
        $scope.changeOver('armada');
       //or do anything 

    });

plunker demo link

Upvotes: 1

Related Questions