$ rootScope。$ broadcast不工作

时间:2016-02-26 05:22:33

标签: angularjs angularjs-directive angular-broadcast

我正在尝试使用$ 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中,它将新数组传递给服务方法。然后它尝试使用行$rootScope.$broadcast('dataPassed', newData)

广播它以进行更改

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

注意 - 我之前的问题How to transfer data between controllers无法给予我任何帮助。

修改

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

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

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

5 个答案:

答案 0 :(得分:3)

使用$ 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);
        });
    }
};

答案 1 :(得分:2)

你应该让听众听广播事件。广播事件不会直接在视图html上直接更新您的视图数据。您必须在范围上使用$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;
    })
};

答案 2 :(得分:0)

你应该听你在播放的内容:

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

此参考可能有所帮助:Why do we use $rootScope.$broadcast in AngularJS?

答案 3 :(得分:0)

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

以下是使用$rootscopehttp://plnkr.co/edit/MBzDMRll5Z4CjusY5QLN?p=preview

的plunker
<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>

答案 4 :(得分:0)

您犯了一个非常小但非常有效的错误。从此更改您的听众:

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

对此:

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

在任何分派的AngularJS作用域事件上,每个侦听器的第一个参数是一个$ event对象。

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

相关问题