要解决此问题,请使用publish/subscribe pattern,它允许获得松散耦合架构。
在 AngularJS 应用程序中,一个很棒的库是 postaljs,它可以轻松实现这种模式:
在app.config 处定义一个$bus $scope 变量,该变量可在应用程序的所有位置访问:控制器、指令...
app.config(function($provide) {
$provide.decorator('$rootScope', [
'$delegate',
function($delegate) {
Object.defineProperty($delegate.constructor.prototype,
'$bus', {
get: function() {
var self = this;
return {
subscribe: function() {
var sub = postal.subscribe.apply(postal, arguments);
self.$on('$destroy',
function() {
sub.unsubscribe();
});
},
channel: function() {
return postal.channel.apply(postal, arguments);
},
publish: function() { postal.publish.apply(postal, arguments); }
};
},
enumerable: false
});
return $delegate;
}
]);
});
发布
发布更新的项目。
var channel = $scope.$bus.channel('myresources');
channel.publish("item.updated", data);
在更新列表上发布
var channel = $scope.$bus.channel('myresources');
....
channel.publish("list.updated", list);
订阅
需要通知“myresources”频道上的事件的控制器/指令。
var channel = $scope.$bus.channel("myresources");
....
//The wildcard * allow be notified on item/list. updated
channel.subscribe("*.updated", function(data, envelopment) {
doOnUpdated();
});