Update View when Scope changes Angular js

2.6k Views Asked by At

I am working on an angular social app where i have few issues related to scope binding. I have a scope data coming from http service which lists user's subscriber. Whenever in search user search for any user and wants to add him then at this time i make a http call and return updated data of subscriber list. But it doesn't update in view without refreshing the page. I can use interval for this but i don't think it would be the solution because it will put more load to my server by making regular http requests.

JS

 this.loadsubscribers = function (){
 myService.subscriber().then(function(response){
     $scope.subscriber = response.data;         
    });
 }

 // i can make interval call for getting subscriber list but this will put load to my server.  

 $interval(function(){
  this.loadsubscribers();
 }.bind(this), 10000);   

this.loadsubscribers();

i need to update this scope when user click on add subscriber button: Here when user click on add subscriber checkit function get called and add that user to subscriber list by making http call . aftre saving data i return the current list of subscriber to http success . But it is not updating the view.

$scope.checkit = function(value,id,firstname,str){      

    if(text === 'get along'){
    $http.post(baseurl+"ajax/subscriber_post", "subscriber_id="+value).success(function(data){
       //here i have to update scope subscriber and 
       // refresh view  as you can see i am doing it but it doesn't update view.  
      $scope.subscriber =data; 
      growl.addSuccessMessage( firstname+" is your fellow now");    
      $scope.datatocheck.push(value);
      $scope.Checkfriend(value); 
    });
}

interval is working but i don't wan't to use it. Well what would be the best way to do this when data doesn't want any synchronous update.

2

There are 2 best solutions below

1
On

Try this:

$scope.$eval(function() {
    $scope.subscriber = data;
});

If you still encounter digest loop issues, try $evalAsync instead of $eval.

0
On

Change this line:

$scope.subscriber =data; 

To this:

$scope.$apply(function() {
    $scope.subscriber =data; 
});