How to capture the event of ng-change?
Capture event beforehand
If you need the ng-change functionality but also want to get the element being changed you could also use ng-focus to capture the element before change.
<select ... ng-focus="setFocus($event)" ng-change="alert()" ... />
Expanded example below:
<!DOCTYPE html>
<html>
<head>
<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) {
if ($scope.currentElement) {
alert($scope.currentElement.value);
}
}
$scope.setFocus = function(event) {
$scope.currentElement = event.target;
}
$scope.cancelFocus = function(event) {
$scope.currentElement = false;
}
});
</script>
</head>
<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()" ng-focus="setFocus($event)" ng-blur="cancelFocus($event)" ng-options="value for value in names">
</select>
</div>
</body>
</html>
ng-change
is not a directive for handling the change event (I realize that this is confusing given the name). So this is as expected. Github source
If you need to get the event, you can use ng-click instead:
<!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>
ngMouse, ng-change does not provide an event object.
But my suggestion is to create another variable, assign $event
to that, then pass it via 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