我正在尝试从ChartJS
控制器检索用户数据时加载dashboard
图表指令。
仅当我在broadcast
上时刷新页面时才会收到dashboard
。如果我点击dashboard
链接并转到dashboards
页面,则不会发送广播。
为什么在刷新仪表板页面时广播,而不是在我路由到它时广播?
路由:
state('dashboard', {
url : '/dashboard',
templateUrl: '/html/pages/dashboard.html',
controller: 'dashboardCtrl',
resolve : {
ProfileLoaded : function ($rootScope) {
return $rootScope.loadProfile();
}
}
});
Dashboard.html:
<div class="dashboard">
<!--Show Chart-->
<chart></chart>
</div>
图表指令HTML:
<div>
<div class="charts chart_1">
<canvas id="chart" width="300" height="300"></canvas>
</div>
</div>
控制器:
angular
.module('DDE')
.controller('dashboardCtrl', ['$rootScope', '$scope',
function($rootScope, $scope) {
/*
Get User Dashboard
*/
$scope.getDashboard = function() {
Dashboard.getDashboard({
user_id : $rootScope.me.id
}).success(function(res) {
populateChart(res);
}).error(function(err){});
};
function populateChart (dashboard_data) {
$rootScope.safeApply(function () {
$scope.$broadcast('dashboard-ready', dashboard_data);
});
}
}
]);
指令:
angular
.module('DDE')
.directive('chart',['$http', function ($http) {
return {
restrict: 'E',
replace: true,
transclude: true,
templateUrl: '/html/directives/charts.html',
link: function(scope, elem, attr){
scope.init = function(args) {
angular.element(document).ready(function () {
drawChart(args);
});
};
//Not fired: Broadcast not received
scope.$on('dashboard-ready', function(event, args) {
scope.init(args);
});
}
}
}]);
其他:stateProvider
的负载配置文件承诺:
$rootScope.loadProfile = function () {
return Me.getProfile({user_id : Cookies.get('user_id')}).success(function (res) {
$rootScope.me = res;
}).error(function (err) {
console.log('Error: ', err);
});
};
编辑:我尝试使用$timeout
来延迟指令。这解决了广播问题(意味着它现在由指令接收),但是给了我一个新的错误:
TypeError:无法读取未定义的属性“call”
function populateChart (dashboard_data) {
$rootScope.safeApply(function () {
$timeout(function () {
$rootScope.$broadcast('dashboard-ready', dashboard_data);
}, 500);
});
}