AngularJS触发ng更改不起作用

AngularJS trigger ng-change not working

本文关键字:不起作用 ng 触发 AngularJS      更新时间:2023-09-26

我只想在每次单击按钮时触发一个更改。更改只会提醒一条文本。但是触发器不起作用,请帮忙。

这是代码:

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

试试这个

 <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可以解决您的问题。

您可以这样做:-

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

此处为工作副本