有没有办法从 Controller 内部的函数调用自定义指令函数。
var m=angular.module('myApp',[]).controller('test',function($scope){
//here i want to call input directive
});
m.directive('input', function() {});
最佳答案
要调用指令函数,您需要使用事件调度:
var m=angular.module('myApp',[]).controller('test',function($rootScope){
$rootScope.$emit('event-response', result);
...
});
m.directive('input', function($rootScope) {
...
$rootScope.$on('event-response', function (args) {
//function call...
});
.....
});
更新
我们可以使用共享作用域将函数从指令添加到父 Controller 。 它不太可能从父 Controller 范围继承,因为这种方式会产生非常强的耦合,并且您需要记住在重用此指令时您是从父 Controller 继承的。
var m=angular.module('myApp',[]).controller('test',function($scope){
$scope.myFunc() // available from `input` directive
...
});
m.directive('input', function() {
return {
scope: false, // scope is shared with parent controller
controller: function($scope) {
$scope.myFunc = function() {
...
};
}
};
});
关于javascript - 如何在angularjs中以编程方式调用自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32754852/