AngularJS将数据广播到iframe

时间:2019-01-17 06:29:38

标签: angularjs

如何从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结果相同。

1 个答案:

答案 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;
    });
});