我想获得$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)
我不知道为什么它没有广播变化来查看.有没有其他方式来广播变化?
注意-
我早先的问题How to transfer data between controllers无法给我任何帮助.
编辑
到目前为止,我已经改变了听众 –
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",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,sharedService,$rootScope) { var shareData = sharedService; $scope.products = sharedService.values; $scope.shareData = sharedService; var data = { "query": "grocery","sortDirection": "asc" }; serviceProvider.getDatas(data).then(function (response) { sharedService.setValues(response.data.data); }); } function searchProductsController($scope,$rootScope) { $scope.submit = function () { var data = { "query": $scope.searchText,"sortDirection": "asc" }; serviceProvider.getDatas(data).then(function (response) { sharedService.setValues(response.data.data); }); } };