AngularJS选择更改触发器

时间:2016-05-06 06:35:31

标签: javascript jquery angularjs

我正在尝试创建一个脚本,将一个选择标记模型的值复制到另一个,然后使用复选框触发其ng-change函数。当您单击复选框时,它会复制值,但触发器不再起作用。似乎设置模型的值和执行触发器之间存在冲突,因为其中任何一个都失败了。

这是我的代码:

<!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>

以下是plunkr网址:http://plnkr.co/edit/zErS4DaTgR79SBLbtGOy?p=preview

1 个答案:

答案 0 :(得分:1)

在DOM正文中,您应该像这样更改此行。

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

并使用watch更改复选框值

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

    });

plunker demo link