I am trying to get $rootScope.$broadcast to refresh my view. 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. Then it is trying to broadcast it for the changes with the line- $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. You should have $scope.$on to listen to that event.
Edit: Update working code for question requirement