I have a service, which should save me the specific data that I load from a JSON file. I want the data to show on the page as soon as it's received. I created a $scope variable to be equal to the data in the service, the data is not shown immediately on the page.
I only achieved my goal when using: angular.copy(response.data, this.animals)
,
but I do not understand why it is not working when I am using: this.animals = response.data
. I would like to know why this is happening and what is the difference.
module.service("animalService", function($http) {
this.animals=[];
$http.get('animals.json').then(function(response) {
//this.animals = response.data ----> not working
angular.copy(response.data, this.animals)
});
});
module.controller("animalController", function($scope, animalService) {
//$scope.animals is what I use to create a table in html
$scope.animals = animalService.aniamsl;
});
You are not doing it right, try:
module.service("animalService", function($http) {
return $http.get('animals.json')
});
module.controller("animalController", function($scope, animalService) {
animalService.then(function(res){
$scope.animals = res.data
});
});
any http
response returns promise
, and what it means is that the data would come asynchronously
. As per my understanding using angular.copy
triggers a digest
cycle and so the changes are detected but it's not at all a good practice. Prefer promise
handling as I have shown in the above code
Since the variable is populated as a promise
and it is to be used by other controller
, I would suggest to use events such as $rootScope.emit
and $rootScope.on
so that the controllers
are notified about the change in value after $http
is completed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With