2017-05-03 70 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