How do I capture the ng-change event?

Here's my code, but it $event

's undefined. Does anyone know how I can capture the event?

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

      

+3


source to share


3 answers


ng-change

is not a directive to handle the change event (I understand 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>
      

Run codeHide result


+2


source


ngMouse, ng-change does not provide an event object . But you can create another variable and assign $ event to it. then pass it through ng-change

. This is my proposal



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

Run codeHide result


More details

+1


source


You can't, this answer is taken from a quick google search result:

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.

      

0


source







All Articles