【发布时间】:2014-07-02 20:02:51
【问题描述】:
我正在使用具有隔离范围的指令在 angularjs 中创建自定义图表小部件。这个想法是每个小部件在收到有关如何创建自己的基本配置信息后应该能够独立存在。
小部件将通过侦听“update.data”事件与应用程序的其他部分进行通信。触发事件时,小部件会根据可用的新配置信息(通过事件对象传递)刷新其数据(调用服务器)。
创建的示例小部件如下
ng.directive('metricOverview', ['Report', function(Report) {
return {
restrict: 'EA',
//replace: true,
scope: {
title: '@',
metrics: '=',
report: '@'
},
templateUrl: 'scripts/widgets/metric-overview/metric-overview.html',
controller: function($scope, $element)
{
},
link: function(scope, element, attrs) {
scope.$on("update.data", function()
{
Report.overview({metric: scope.metric, report: scope.report})
.$promise.then(function(result) {
console.log(result);
$(document).trigger("chart.refresh", result);
});
});
}
};
}]);
我的问题是在哪里触发“update.data”事件最合适。例如,当页面加载并且 DOM 准备就绪时,我希望触发此事件,并且所有加载的小部件都应该能够侦听它并自行更新。我无法触发 rootScope 上的事件,因为它在指令的隔离范围内不可访问。
做了一些研究,但我发现的大部分内容都依赖于使用全局/父范围,由于指令的孤立性质,这不能满足我的目的
解决此问题的最佳方法是什么?
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope