2017-05-03 106 views
3

這是我的代碼,但是$event未定義。有誰知道我怎麼捕捉這個事件?如何捕獲ng-change的事件?

<!DOCTYPE html> 
<html> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 

<script type="text/javascript"> 

    var app = angular.module("myApp", []); 
    app.controller("myCtrl", function($scope) { 
     $scope.alert = function ($event){ 
      alert($event); 
     } 
    }); 
</script> 

<body ng-app="myApp" ng-controller="myCtrl"> 
<div ng-init="names=['A', 'B', 'C']"> 
    <select class="form-control input-sm" ng-model="fda" ng-change="alert($event)" ng-options="value for value in names"> 
    </select> 
</div> 
</body> 

</html> 

回答

2

ng-change不是處理變化事件(我知道這很容易混淆的名稱是)一個指令。所以這是預期的。 Github source

如果你需要獲得的情況下,你可以改用NG點擊:

<!DOCTYPE html> 
 
<html> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 

 
<script type="text/javascript"> 
 

 
    var app = angular.module("myApp", []); 
 
    app.controller("myCtrl", function($scope) { 
 
     $scope.alert = function ($event){ 
 
      alert($event); 
 
     } 
 
    }); 
 
</script> 
 

 
<body ng-app="myApp" ng-controller="myCtrl"> 
 
<div ng-init="names=['A', 'B', 'C']"> 
 
    <select class="form-control input-sm" ng-model="fda" ng-click="alert($event)" ng-options="value for value in names"> 
 
    </select> 
 
</div> 
 
</body> 
 

 
</html>

0

你不能,this answer從快速谷歌搜索結果採取:

ng-change is not a directive for handling the change event 
(I realize that this is confusing given the name), but is actually 
instead notified when ngModelController.$setViewValue() is called 
and the value changes (because ng-change adds a listener to the 
$viewChangeListeners collection). So this is as expected. 
1

ngMouse,ng-change不提供事件對象。但是您可以創建另一個變量併爲其分配$事件。然後通過ng-change傳遞它。這是我的建議

<!DOCTYPE html> 
 
<html> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 

 
<script type="text/javascript"> 
 

 
    var app = angular.module("myApp", []); 
 
    app.controller("myCtrl", function($scope) { 
 
     $scope.alert = function ($event){ 
 
      alert($event); 
 
     } 
 
    }); 
 
</script> 
 

 
<body ng-app="myApp" ng-controller="myCtrl"> 
 
<div ng-init="names=['A', 'B', 'C']"> 
 
    <select class="form-control input-sm" ng-click="event = $event" ng-model="fda" ng-change="alert(event)" ng-options="value for value in names"> 
 
    </select> 
 
</div> 
 
</body> 
 

 
</html>

More details