How can I send my $scope
object from one controller to another using .$emit
and .$on
methods?
function firstCtrl($scop
You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit
or $broadcast
to inform other controllers about it.
In my case, I had to make http calls through my service, so I did something like this :
function ParentController($scope, testService) {
testService.getList()
.then(function(data) {
$scope.list = testService.list;
})
.finally(function() {
$scope.$emit('listFetched');
})
function ChildController($scope, testService) {
$scope.$on('listFetched', function(event, data) {
// use the data accordingly
})
}
and my service looks like this
app.service('testService', ['$http', function($http) {
this.list = [];
this.getList = function() {
return $http.get(someUrl)
.then(function(response) {
if (typeof response.data === 'object') {
list = response.data.results;
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
}])