2017-05-03 27 views
0

這是我的代碼,但是ng-change從來沒有被調用過。有誰知道爲什麼?由於如何在ng-change事件中調用預定義的JavaScript函數?

<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> 
+1

你已經寫一個函數。例如:ng-change =「changefunction()」並在你的控制器中$ scope.changefunction = function(){alert(「changed」); } –

+0

我認爲這是一個很好的問題,但它可能是'如何在ng-change事件中調用預定義的JavaScript函數?'我已經回答了這個意見 –

回答

2

你需要有一個控制器和它內部的相應的功能,

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>

+0

謝謝@Sajeetharan,它的工作原理。但我仍然想知道我是否可以在沒有控制器的情況下調用函數,如我的代碼片段。 – zjffdu

+1

@zjffdu不,你不能沒有控制器。 – Sajeetharan

0

只需添加這行你的騙局troller $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>

相關問題