我在application.js
项目的AngularJS
文件中声明了一项服务。它看起来像这样:
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;
});
我使用上述服务在Controllers
的2个之间传递变量。调用服务的控制器在这里:
$scope.buildDemo = function () {
interfaceService.demo(device, template, integ, language);
$rootScope.template = template;
$rootScope.themeFolder = template;
$state.go("MainPage", {
"themeName": $rootScope.themeFolder
});
}
当用户点击view
<div id='build-btn' ng-click='buildDemo()'>Go</div>
我遇到的问题是当我点击按钮时我的视图没有更新。我必须再次点击它才能看到任何变化。有谁知道是什么原因造成的? URL更新和新视图进入页面,但在我点击&#34; Go&#34;之前,基于服务中设置的参数应显示的元素是不可见的。按钮第二次。
答案 0 :(得分:1)
首次点击handleBroadcast
事件被广播但未被任何人接收,因为当您按下“开始”按钮时,此时会发生状态转换并加载模板及其控制器。当控制器实例化时,它会在$on
事件上使用handleBroadcast
注册侦听器事件。
我建议你等到广播事件直到控制器&amp;它的底层视图得到渲染。这可以通过利用$state.go
方法返回的保证来完成。转换成功时完成。
<强>代码强>
$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;
});
}