• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

javascript – angular中使用了broadcast和on,为什么on里面的代码不是每次都成功运行?

php 搞代码 3年前 (2022-01-23) 23次浏览 已收录 0个评论
文章目录[隐藏]
<code>var app = angular.module('gzmu', ["ngRoute",'chart.js']);app.run(function ($rootScope, $http) {    $http({        method: 'GET',        url: 'datacon/user_info.php',    }).success(function (response) {            $rootScope.userinfo = response[0];        console.log($rootScope.userinfo)        $rootScope.$broadcast("userinfo", response[0]);    })});app.controller('data', function ($scope, $http, $rootScope) {    $scope.usernamea='';    $scope.$on("userinfo",        function (event, msg) {            console.log(msg);            if(msg){                $scope.usernamea = msg.user;                console.log($scope.usernamea)                alert($scope.usernamea)            }            else{                alert(msg)            }        });});</code>

如题,on里面的代码为什么不会每加载一次页面都运行一次?

回复内容:

<code>var app = angular.module('gzmu', ["ngRoute",'chart.js']);app.run(function ($rootScope, $http) {    $http({        method: 'GET',        url: 'datacon/user_info.php',    }).success(function (response) {            $rootScope.userinfo = response[0];        console.log($rootScope.userinfo)        $rootScope.$broadcast("userinfo", response[0]);    })});app.controller('data', function ($scope, $http, $rootScope) {    $scope.usernamea='';    $scope.$on("userinfo",        function (event, msg) {            console.log(msg);            if(msg){                $scope.usernamea = msg.user;                console.log($scope.usernamea)                alert($scope.usernamea)            }            else{                alert(msg)            }   <div>本文#来源gaodai.ma#com搞##代!^码7网</div><pre>搞代gaodaima码

});});

如题,on里面的代码为什么不会每加载一次页面都运行一次?

主要原因是在app的run中broadcast其实是一个异步操作,如果说data这个Controller在run中的请求成功并且broadcast之前创建,就会成功调用,否则它接收不到root广播过来的信息


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:javascript – angular中使用了broadcast和on,为什么on里面的代码不是每次都成功运行?
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址