如何在下面的代码中调用指令中的 Controller 方法:
app.controller("main",['$scope','$http',function($scope,$http){
$scope.SelectCollege = function (){
//Code to search college
}
}]);
指令
angular.module('angucomplete', [] )
.directive('angucomplete', function ($parse, $http, $sce, $timeout) {
link: function($scope, elem, attrs) {
$("#search_value").autocomplete({
source: $scope.localData,
select: function( event, ui ) {
//How to call controller's method here
}
});
}
});
最佳答案
您可以将 Controller 包含在指令属性中
Controller 选项采用字符串或函数。当设置为字符串时,字符串的名称为 用于查找在我们的应用程序中其他地方注册的 Controller 构造函数:
angular.module('myApp', [])
.directive('myDirective', function() {
restrict: 'A', // always required
controller: 'SomeController',
link: function(scope, element, attrs, SomeController) {
SomeController.doSomething(scope);
},
})
// elsewhere in our application
// either in the same file or another
// one included by our index.html
angular.module('myApp')
.controller('SomeController', function($scope, $element, $attrs, $transclude) {
// controller logic goes here
})
关于javascript - 从 Directive AngularJS 调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25176207/