[英]angular add function to $element in directive
I have a page with two directives. 我有一个带有两个指令的页面。 I need to invoke a function in one directive from the other.
我需要从另一个指令中调用一个函数。 I have added the function to the $element object of the first directive and used jQuery to invoke it from the other.
我已经将该函数添加到第一个指令的$ element对象中,并使用jQuery从另一个指令中调用它。 Is this the right approach or should I be using a context object shared by both directives?
这是正确的方法还是我应该使用两个指令共享的上下文对象?
//inside directive 1 link fn
$element[0].foo = function(){
console.log("test");
}
...
//inside directive 2 link fn
$('.className').foo()
The two directives are elements on a page with a shared controller. 这两个伪指令是具有共享控制器的页面上的元素。 Each has an isolated scope.
每个都有一个隔离的范围。 This seems to work well.
这似乎运作良好。 Are there any reasons why I should not do this?
有什么原因我不应该这样做吗?
This is not the way you should do it. 这不是您应该这样做的方式。 Try to avoid using $element, it does DOM manipulations which are slow and Angular takes care of by itself.
尽量避免使用$ element,它会执行DOM操作,这很慢,并且Angular会自己处理。 To invoke a function in directiveB, triggered from directiveA, you better make a service.
要在指令B中调用从指令A触发的函数,最好提供服务。
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');
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.