如果知道特定指令的ID,是否可以直接调用特定指令上的方法?我知道如何通过侦听器事件(广播或发出)来完成这个任务。我想我可以使用jQuery进行操作,但我希望只能通过角度进行操作。此外,我希望避免侦听器事件,因为该指令的每个实例都必须确定该特定事件是否“属于”它们,这似乎是“浪费”的。
<custom-element ce-Id="5"></custom-element>
<custom-element ce-Id="6"></custom-element>
<custom-element ce-Id="7"></custom-element>
<custom-element ce-Id="8"></custom-element>
<custom-element ce-Id="9"></custom-element>
<custom-element ce-Id="10"></custom-element>因此,使用上面的示例,指令ce-Id="6“上的事件(例如单击事件)是否有可能在没有使用侦听器的情况下触发特定发生在ce-Id="7”上的事件?
发布于 2014-05-05 14:56:31
您可以在指令的工厂函数中定义自定义API,并跟踪订阅者。此代码只运行一次。也可以将其移动到服务中。
示例:
app.directive('customElement', function() {
var subscribers = {};
var subscribe = function(id, callback) {
subscribers[id] = callback;
};
var unsubscribe = function(id) {
subscribers[id] = null;
};
var notify = function(id) {
var target = parseInt(id) + 1;
var action = subscribers[target];
if (action) action();
};
var api = {
subscribe: subscribe,
unsubscribe: unsubscribe,
notify: notify
};
return {
restrict: 'E',
template: '<div>I am custom element: {{ ceId }}</div>',
scope: {
ceId: '@',
},
link: function(scope, element, attrs) {
var id = scope.ceId;
if (!id) return;
var onReceive = function() {
console.log('customElement ' + id + ' has received notification.');
};
api.subscribe(id, onReceive);
var onClick = function() {
scope.$apply(function () {
api.notify(id);
});
};
element.on('click', onClick);
scope.$on('$destroy', function() {
element.off('click', onClick);
api.unsubscribe(id);
});
}
};
});Demo:http://plnkr.co/edit/2s1bkToSuHPURQUcvZcd?p=preview
https://stackoverflow.com/questions/23474938
复制相似问题