1

Here's my code, however ng-change is never called. Does anyone know why ? Thanks

<html ng-app="">

<head>
</head>

<body data-ng-init="names=['A', 'B', 'C']">

<script src="resources/js/angular/angular.min.js"></script>
<script src="resources/js/angular/angular.min.js.map"></script>

<select class="form-control input-sm"
        ng-model="fda"
        ng-change="alert('changed')"
        ng-options= "value for value in names" >
</select>


</body>

</html>
2
  • 1
    You've to write a function. Eg: ng-change = "changefunction()" and in your controller $scope.changefunction = function() { alert("changed"); } Commented May 3, 2017 at 10:58
  • I think it's a good question, But it could be how to call predefined JavaScript function in ng-change event? I have answered for this sense Commented May 3, 2017 at 11:14

2 Answers 2

2

You need to have a controller and a corresponding function inside of it,

app.controller("myCtrl", function($scope) {
$scope.alert = function (){
    alert("changed");
}
});

DEMO

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
 $scope.alert = function (){
    alert("changed");
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></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('changed')" ng-options="value for value in names">
     </select>
    </div>
</body>

</html>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Sajeetharan , it works. But I still want to know whether I can call function inline without controller like my code snippet.
@zjffdu No you cannot do without a controller.
why in your ng-change, you're calling alert() and passing in 'change'? That doesn't seem to be used in your $scope.alert() reference at all.
0

Just add this line in your controller $scope.alert = alert.bind(window);

var app = angular.module("myApp", []); 
app.controller("myCtrl", function($scope) {      
  $scope.alert = alert.bind(window);
   });
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></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('changed')" ng-options="value for value in names">
     </select>
    </div>
</body>

</html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.