gpt4 book ai didi

javascript - Angular $broadcast 仅在页面刷新时填充数据

转载 作者:行者123 更新时间:2023-11-28 06:32:29 24 4
gpt4 key购买 nike

我正在尝试使用 $broadcast$on 将数据从 Controller 传递到指令。

当我刷新页面时,数据仅出现在指令的 HTML 模板上。当我使用嵌入指令路由到 Controller 模板时,它不会出现。

奇怪的是,当我控制台登录时,数据似乎已经收到。我尝试过使用 $timeoutangular.element(document).ready

Controller :

$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;
};

带有嵌入式结果指令的 Controller 页面:

<div class="myPage">
<results></results>
</div>

指令 HTML:

<div>
QUESTIONS: {{questions}} : //Empty array
</div>

控制台日志:您可以看到它有数据:

enter image description here

<小时/>

路由顺序:

   .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

关于javascript - Angular $broadcast 仅在页面刷新时填充数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34583227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com