AngularJS触发ng-change无法正常工作

时间:2016-05-06 04:49:34

标签: javascript jquery angularjs

我只想在点击按钮时触发更改。此更改将仅提醒文本。但是,触发器不起作用请帮助。

以下是代码:

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

以下是plunker的链接: http://plnkr.co/edit/zErS4DaTgR79SBLbtGOy?p=preview

2 个答案:

答案 0 :(得分:1)

试试这个

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

通过添加$ timeout,您的问题就会得到解决。

答案 1 :(得分:-1)

你可以这样做: -

$scope.clickMe = function(){
        var scope = angular.element("#changes").scope();
         scope.changeOver();
         //angular.element(document.getElementById('changes')).triggerHandler('change');

}

工作副本here