Senthil
Senthil

Reputation: 956

Data assign through service not updating in Angular JS

I wrote a service to share and update Datas between controller

myApp.service('Physician',function($http){
 var physicians = [];

 var refresh = function(fetch) {
  physicians = []

  $http({
   url: '/provider/',
   method: 'GET',
  }).success(function (response) {
   $.each(response, function(index, value){
     physicians.push(value);
   });
   console.log(physicians);
  });
 }


return {
 refresh: refresh,
 all: physicians
};
})

I included the above service in my controller

function physicianController($scope, $http, Physician) {
  $scope.physicians = Physician.all
}

Now I have another controller which sharing the Physician service and calling refresh function in it.

function conditionController($scope, $http, Physician) {
  $scope.add = function() {
   Physician.refresh();
  }
}

As soon as the refresh function is called I expect the $scope.physicians in physicianController to be the updated, but its not , any tips will be helpful.

Upvotes: 2

Views: 1101

Answers (1)

Senthil
Senthil

Reputation: 956

@Sergiu Paraschiv's Answer : physicians = [] basically assigns a new reference to the physicians variable. AngularJS relies on it to keep the same reference to be able to keep track of changes. You thus need to empty the array, not reinitialize it. A.splice(0,A.length) should work

Upvotes: 2

Related Questions