gpt4 book ai didi

javascript - AngularJS 服务未更新 View

转载 作者:行者123 更新时间:2023-11-27 23:11:42 25 4
gpt4 key购买 nike

我在 AngularJS 项目中的 application.js 文件中声明了一项服务。它看起来像这样:

application.factory('interfaceService', function ($rootScope, $timeout) {
var interfaceService = {};
interfaceService.lang = "";
interfaceService.dev = ""
interfaceService.theme = "";
interfaceService.integ = "";
//For Integration Type
interfaceService.demo = function (dev, theme, integ, lang) {
this.dev = dev;
this.theme = theme;
this.integ= integ;
this.lang = lang;
this.broadcastItem();
};
interfaceService.broadcastItem = function () {
$timeout(function(){
$rootScope.$broadcast('handleBroadcast');
});
};
return interfaceService;
});

我正在使用上述服务在我的两个 Controller 之间传递变量。调用服务的 Controller 在这里:

        $scope.buildDemo = function () {
interfaceService.demo(device, template, integ, language);
$rootScope.template = template;
$rootScope.themeFolder = template;
$state.go("MainPage", {
"themeName": $rootScope.themeFolder
});
}

当用户点击我的 View 上的div时会触发该函数

<div id='build-btn' ng-click='buildDemo()'>Go</div>

我遇到的问题是,当我单击按钮时,我的 View 没有更新。我必须再次单击它才能看到任何更改。有谁知道这是什么原因造成的吗? URL 更新并且新 View 出现在页面上,但应根据服务中设置的参数显示的元素不可见,直到我再次单击“Go”按钮。

最佳答案

第一次单击 handleBroadcast 事件会被广播,但没有被任何人接收,因为当您按下“GO”按钮时,此时会发生状态转换并加载模板及其 Controller 。当 Controller 实例化时,它会在 handleBroadcast 事件上使用 $on 注册监听器事件。

我建议您等待广播事件,直到 Controller 及其底层 View 得到渲染。这可以通过利用 $state.go 方法返回的 Promise 来完成。转换成功后即完成。

代码

$scope.buildDemo = function() {
//state transition started.
$state.go("MainPage", {
"themeName": $rootScope.themeFolder
}).then(function() {
//state transition completed
//controller instance is available & listener is ready to listen
interfaceService.demo(device, template, integ, language);
$rootScope.template = template;
$rootScope.themeFolder = template;
});
}

关于javascript - AngularJS 服务未更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36139848/

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