angularjs – $rootScope.$broadcast not working
发布时间:2020-12-17 17:25:59 所属栏目:安全 来源:网络整理
导读:我想获得$rootScope.$broadcast来刷新我的观点. 服务是 – var app = angular.module("productsApp",[]) .service("serviceProvider",function ($http) { this.getDatas = function getDatas(data) { return $http({ method: 'POST',url: serviceUrl + '/Get
我想获得$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) 我不知道为什么它没有广播变化来查看.有没有其他方式来广播变化? 注意- 编辑 到目前为止,我已经改变了听众 – 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); }); } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |