[英]Angular $broadcast only populating data on page refresh
我正在尝试使用$broadcast
和$on
将数据从控制器传递到指令。
刷新页面时,数据仅出现在指令的HTML模板上。 当我使用嵌入式指令route
到控制器模板时,它不会出现。
奇怪的是,当我控制台日志时,似乎已收到数据。 我已经尝试使用$timeout
和angular.element(document).ready
控制器:
$http.getDashboardData(...).success(function(res) {
populateResults(res);
...
}
function populateResults (data) {
$rootScope.safeApply(function () {
$rootScope.$broadcast('show-results', data);
});
}
指示:
.directive('results',['$rootScope', function ($rootScope) {
return {
restrict: 'AE',
scope: {},
transclude: true,
templateUrl: '/html/directives/results.html',
link: function(scope, elem, attr){
...
$rootScope.$on('show-results', function(event, args) {
angular.element(document).ready(function () {
scope.init(args);
});
});
scope.init = function (args) {
console.log('ARGS', args); //Has data
scope.questions = args;
};
具有嵌入式results
指令的控制器页面:
<div class="myPage">
<results></results>
</div>
指令HTML:
<div>
QUESTIONS: {{questions}} : //Empty array
</div>
控制台日志:您可以看到其中包含数据:
路由顺序:
.config:
...
state('dashboard', {
url : '/dashboard',
templateUrl: '/html/pages/dashboard.html',
controller: 'dashboardCtrl',
resolve : {
ProfileLoaded : function ($rootScope) {
return $rootScope.loadProfile();
}
}
});
.run:如果用户刷新页面,这将加载配置文件:
$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);
});
};
在指令链接函数中,尝试使用scope。$ on而不是$ rootScope。$ on,并直接使用scope.init而不使用document.ready
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.