我有一个包含两个指令的页面。我需要从一个指令中调用另一个指令中的函数。我已经将该函数添加到第一个指令的$element对象中,并使用jQuery从另一个指令中调用它。这是正确的方法吗?还是我应该使用两个指令共享的上下文对象?
//inside directive 1 link fn
$element[0].foo = function(){
console.log("test");
}
...
//inside directive 2 link fn
$('.className').foo()这两个指令是具有共享控制器的页面上的元素。每一个都有一个独立的作用域。这似乎工作得很好。有什么理由让我不能这么做吗?
发布于 2016-05-25 04:56:04
这两个指令是否共享同一个控制器?如果是这样,您可以从一个指令调用控制器上的函数,该指令将“通知”另一个指令。或者,您可以使用事件,请查看此答案here
发布于 2016-05-25 05:02:05
这不是你应该做的事情。尽量避免使用$element,它做的DOM操作很慢,而且Angular会自己处理。要调用从directiveA触发的directiveB中的函数,最好创建一个服务。
angular.service('Communication', function () {
var _listeners = [];
return {
addListener: function (callback) {
_listeners.push(callback);
},
removeListener: function () {/* Clean up */},
invokeListeners: function (data) {
_listeners.forEach(function (listener) {
listener(data);
});
}
}
});
angular.directive('directiveB', ['Communication', function (Communication) {
return {
restrict: 'AE',
scope: {},
controller: directiveB
};
function directiveB (scope, element, attrs) {
Communication.addEventListener(function (data) { /* Do stuff with data */ });
}
}]);
angular.directive('directiveA', ['Communication', function (Communication) {
return {
restrict: 'AE',
scope: {},
controller: directiveA
};
function directiveA (scope, element, attrs) {
// trigger event in directive B
Communication.invokeListeners('test');
}
}]);https://stackoverflow.com/questions/37423630
复制相似问题