如何从index.html获取用户名?
index.html
{{username}}
索引控制器:
app.controller('index',function($scope,$rootScope,mainService){
$scope.getUsername = funciton(){
mainService.getUsername().then{
function successCallback(response){
$rootScope.username = response.data.username;
}
}
}
})
iframe.html
{{user}}
iframe控制器
app.controller('iframe',function($scope,$rootScope){
$scope.user = $rootScope.username
})
但是{{user}}
什么也不显示
此外,我尝试按服务发布消息,例如dataService.username
结果相同。
答案 0 :(得分:0)
使用$rootScope.$broadcast
引发事件,事件名称的第一个参数,以及传递参数的可选第二个参数。
app.controller('IndexController', function ($scope, $rootScope, MainService) {
$scope.getUsername = function() {
MainService.getUsername().then(function (response) {
$rootScope.$broadcast('username-fetched', { username: response.data.username });
});
};
});
然后使用$scope.$on
在另一个控制器上捕获事件。
app.controller('IframeController', function ($scope) {
$scope.$on('username-fetched', function (event, data) {
$scope.user = data.username;
});
});