如何在下面的代码中调用指令中的controllers方法:
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
}
});
}
});
答案 0 :(得分:1)
假设指令放在控制器范围内(带有ng-controller的元素)
select: function( event, ui ) {
//How to call controller's method here
//Answer: as shown below
$scope.SelectCollege();
}
答案 1 :(得分:1)
您可以在控制器中包含指令属性
控制器选项采用字符串或函数。设置为字符串时,字符串的名称为 用于查找在我们的应用程序中其他位置注册的控制器构造函数:
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
})
答案 2 :(得分:-1)
您可以将控制器的方法传递给指令的范围,如下所示:
<autocomplete on-select="SelectCollege()"></autocomplete>
在你的指令中定义你的范围
scope: {
onSelect: "&onSelect"
}
然后在你的指令中,你只需将其称为:
$scope.onSelect()
或者,如果您的指令位于控制器范围内,则可以在指令中使用$scope.SelectCollege()
和您的指令不会声明自己的范围,而是继承自控制器范围。例如:
<div ng-controller="main">
<autocomplete></autocomplete>
</div>