繁体   English   中英

$ rootScope。$ broadcast不工作

[英]$rootScope.$broadcast not working

我想获得$ rootScope。$ broadcast来刷新我的观点。 服务是 -

var app = angular.module("productsApp", [])
    .service("serviceProvider", function ($http) {
        this.getDatas = function getDatas(data) {
            return $http({
                method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
                    'Authorization': apiKey
                },
                data: data
            })
        }
        return this
    }).factory("sharedService", function ($rootScope) {

        var mySharedService = {};

        mySharedService.values = [];

        mySharedService.passData = function (newData) {
            mySharedService.values = newData;
            $rootScope.$broadcast('dataPassed', newData);
        }

        return mySharedService;
    });

通过控制器调用 -

function searchProductsController($scope, $window, serviceProvider, sharedService) {
    $scope.submit = function () {
        var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
        serviceProvider.getDatas(data).then(function (response) {
            var result = response;
            sharedService.passData(result.data.data);
        });
    }
};

这个控制器中有sharedService.passData ,它将新数组传递给service方法。 然后它尝试使用line- $rootScope.$broadcast('dataPassed', newData)广播它以进行更改$rootScope.$broadcast('dataPassed', newData)

我不知道为什么它没有广播变化来查看。 有没有其他方式来广播变化?

注意 -我之前的问题如何在控制器之间传输数据无法给我任何帮助。

编辑

到目前为止,我已经改变了听众 -

mySharedService.passData = function (newData) {
    $rootScope.$broadcast('dataPassed', newData)
}
$rootScope.$on('dataPassed', function (newData) {
    mySharedService.values = newData;
})

但仍然无法获得更新的观点。

当你使用$ broadcast或$ emit时。 你应该有$ scope。$ on来听这个事件。

$scope.$on('dataPassed', function(){ //code go here });

编辑:更新问题要求的工作代码

var app = angular.module("productsApp", [])
    .service("serviceProvider", function ($http) {
        this.getDatas = function getDatas(data) {
            return $http({
                method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
                    'Authorization': apiKey
                },
                data: data
            });
        }
        return this
    }).factory("sharedService", ['$rootScope', function ($rootScope) {
        var mySharedService = {
            values: [],
            setValues: function(data){
                if(data){
                    mySharedService.values.length = 0;
                    data.forEach(function(item){
                        mySharedService.values.push(item);
                    });    
                }
            }
        };
        return mySharedService;
    }]);      
function GetController($scope, serviceProvider, sharedService, $rootScope) {
    var shareData = sharedService;
    $scope.products = sharedService.values;
    $scope.shareData = sharedService;
    var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
    serviceProvider.getDatas(data).then(function (response) {
        sharedService.setValues(response.data.data);
    });
}
function searchProductsController($scope, $window, serviceProvider, sharedService, $rootScope) {
    $scope.submit = function () {
        var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
        serviceProvider.getDatas(data).then(function (response) {
            sharedService.setValues(response.data.data);
        });
    }
};

你应该让听众听广播的事件。 广播事件不会直接在视图html上直接更新您的视图数据。 您必须在范围$on使用$on来绑定范围上的事件。 在它的回调函数内。 您将获得获得广播数据的好处,并再次将检索数据分配给范围变量以获得更新的绑定。

var app = angular.module("productsApp", [])
  .service("serviceProvider", function($http) {
  this.getDatas = function getDatas(data) {
    return $http({
      method: 'POST',
      url: serviceUrl + '/GetProductsByCategoryOrName',
      headers: {
        'Authorization': apiKey
      },
      data: data
    })
  }
  return this;
}).factory("sharedService", ['$rootScope', function($rootScope) {

  var mySharedService = {};

  mySharedService.values = [];

  mySharedService.passData = function(newData) {
    mySharedService.values = newData;
    $rootScope.$broadcast('dataPassed', newData)
  }

  return mySharedService;
}]);

function GetController($scope, serviceProvider, sharedService, $rootScope) {
  var data = {
    "query": "grocery",
    "categoryId": "976759",
    "pageIndex": 0,
    "sortDirection": "asc"
  };
  serviceProvider.getDatas(data).then(function(response) {
    sharedService.passData(response.data.data);
  });
  //listener should register when controller loads
  $scope.$on('dataPassed', function(event, newData) {
    sharedService.values = newData;
    $scope.products = sharedService.values;
  })
}

function searchProductsController($scope, $window, serviceProvider, sharedService, $rootScope) {
    $scope.submit = function() {
      var data = {
        "query": $scope.searchText,
        "categoryId": "976759",
        "pageIndex": 0,
        "sortDirection": "asc"
      };
      serviceProvider.getDatas(data).then(function(response) {
        var result = response;
        sharedService.passData(result.data.data);
      });
    }
    //listener should register when controller loads
    $scope.$on('dataPassed', function(event, newData) {
      console.log(newData);
      sharedService.values = newData;
    })
};

你应该听你在播放什么:

$rootScope.$on('dataPassed', function(data){
console.log(data);
});

这个参考可能会有所帮助: 为什么我们在AngularJS中使用$ rootScope。$ broadcast?

@Manoz和你之前的回答一样,我已经给你答案了。 我也为此更新了plunker。 至于使用$rootscope. ,你有2个参数,其中一个是事件,下一个是你正在广播的数据。 我在两个答案中嘲笑你的api电话,让你更加理解。

这是使用$rootscopehttp$rootscope

<html>

   <head>
      <title>Angular JS Controller</title>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "app" >

           <div ng-controller="searchProductsController">
             <input ng-model="searchText"/>
                <button ng-click="setPlace(searchText)">Enter Search id</button>
            </div>
            <div ng-controller="GetController">
              <div ng-repeat="product in products">
                                <h3>{{product.name}}</h3>
                </div>
              </div>
      </div>


<script>
         var app = angular.module('app', []);
         app.run(['$rootScope', function($rootScope){
              $rootScope.test = 123;
            }]);

        app.factory("Service", function ($rootScope) {
            function passData(newData) {
              alert('i am here');
               $rootScope.$broadcast('dataPassed', newData);
            }
            return {
                passData: passData
            }
        }).factory("dataService",function($http){//mock for getting values from api
          return{
            getComments:function (roomid){
                   if(roomid==1){
                     var data = [{"name":"alex","place":"kathmandu"},{"name":"god","place":"seattle"}];
                     return data;
                   }
                   if(roomid==2)
                   {
                     var newdata = [{"name":"newname","place":"kathmandu"},{"name":"newname2","place":"seattle"}];
                     return newdata;
                   }
              }
          }
        });
        app.controller('searchProductsController',function($scope, Service,$http,dataService) {
            $scope.setPlace = function (searchText) {
                var newdata = dataService.getComments(searchText);
                Service.passData(newdata);
            }
        })
        .controller('GetController',function($scope, Service,$rootScope) {
          $rootScope.$on('dataPassed', function (event,args) {
                $scope.products = args;
            })
        })
              </script>

   </body>
</html>

你犯了一个非常小但非常有效的错误。 从这个改变你的听众:

$rootScope.$on('dataPassed', function (newData) {
    mySharedService.values = newData;
});

对此:

$rootScope.$on('dataPassed', function ($event, newData) {
    mySharedService.values = newData;
});

在调度的任何AngularJS范围事件上,每个侦听器的第一个参数是一个$ event对象。

我很惊讶,有这么多答案的一个老问题没有注意到真正的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM