[英]$rootScope.$broadcast not working
I am trying to get $rootScope.$broadcast to refresh my view. 我想获得$ rootScope。$ broadcast来刷新我的观点。 The service is- 服务是 -
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;
});
Invoking through controller- 通过控制器调用 -
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);
});
}
};
here in this controller sharedService.passData
which passes new array to service method. 这个控制器中有sharedService.passData
,它将新数组传递给service方法。 Then it is trying to broadcast it for the changes with the line- $rootScope.$broadcast('dataPassed', newData)
然后它尝试使用line- $rootScope.$broadcast('dataPassed', newData)
广播它以进行更改$rootScope.$broadcast('dataPassed', newData)
I don't know why it is not broadcasting the changes to view. 我不知道为什么它没有广播变化来查看。 Is there any other way to broadcast the changes? 有没有其他方式来广播变化?
Note- My earlier question How to transfer data between controllers couldn't get me any help. 注意 -我之前的问题如何在控制器之间传输数据无法给我任何帮助。
Edit 编辑
So far I've changed in the listeners- 到目前为止,我已经改变了听众 -
mySharedService.passData = function (newData) {
$rootScope.$broadcast('dataPassed', newData)
}
$rootScope.$on('dataPassed', function (newData) {
mySharedService.values = newData;
})
But still can't get refreshed view. 但仍然无法获得更新的观点。
When you use $broadcast or $emit. 当你使用$ broadcast或$ emit时。 You should have $scope.$on to listen to that event. 你应该有$ scope。$ on来听这个事件。
$scope.$on('dataPassed', function(){ //code go here });
Edit: Update working code for question requirement 编辑:更新问题要求的工作代码
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);
});
}
};
You should have put a listeners to listen to the broadbasted event. 你应该让听众听广播的事件。 Broadcasted event would not directly update your view data directly on view html. 广播事件不会直接在视图html上直接更新您的视图数据。 You have to use $on
over scope to bind events on scope. 您必须在范围$on
使用$on
来绑定范围上的事件。 Inside a callback function of it. 在它的回调函数内。 You would get an benefit to get broadcasted data & re assign that retrieve data to scope variable again to get updated binding. 您将获得获得广播数据的好处,并再次将检索数据分配给范围变量以获得更新的绑定。
Code 码
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;
})
};
You should listen what you are broadcasting : 你应该听你在播放什么:
$rootScope.$on('dataPassed', function(data){
console.log(data);
});
This reference may help : Why do we use $rootScope.$broadcast in AngularJS? 这个参考可能会有所帮助: 为什么我们在AngularJS中使用$ rootScope。$ broadcast?
@Manoz as for you previous answer also, i had given you the answer. @Manoz和你之前的回答一样,我已经给你答案了。 I have updated the plunker for that as well. 我也为此更新了plunker。 And as for using $rootscope.
至于使用$rootscope.
, you have 2 params, in which one is event and the next is the data you are broadcasting. ,你有2个参数,其中一个是事件,下一个是你正在广播的数据。 I have mocked your api call in both the answers to make you more understand. 我在两个答案中嘲笑你的api电话,让你更加理解。
Here is plunker using $rootscope
: http://plnkr.co/edit/MBzDMRll5Z4CjusY5QLN?p=preview 这是使用$rootscope
: http : $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>
You've made a very little, but very effective, mistake. 你犯了一个非常小但非常有效的错误。 Change your listener from this: 从这个改变你的听众:
$rootScope.$on('dataPassed', function (newData) {
mySharedService.values = newData;
});
To this: 对此:
$rootScope.$on('dataPassed', function ($event, newData) {
mySharedService.values = newData;
});
On any AngularJS scope event dispatched, the first argument for every listener is one $event object. 在调度的任何AngularJS范围事件上,每个侦听器的第一个参数是一个$ event对象。
I'm surprised that one old question, with this many answers, haven't noticed the real issue. 我很惊讶,有这么多答案的一个老问题没有注意到真正的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.