Ângelo Rigo
Ângelo Rigo

Reputation: 2159

Template not updating after calling a angularjs controller method

I could not update the template after a search using a controller method.

I have a controller wich list data to a template, correctly if no search is performed. The data is retrieved from a service.

When i do search by month and origin the result after calling the search method in the console.log is the right data, but the html template does not show this data it shows the non-filtered data.

I try to return the $scope.data, or scope.apply, it did not work.

How can i update the template with the filtered data ?

The controller with the search method :

.controller('AcpCtrl', function($scope, ApiAcpFactory, $ionicLoading, $timeout, $http) {  
  $scope.data = null;
  $ionicLoading.show({noBackdrop: true,template: '<p>Searching ...</p>'});
  ApiAcpFactory.getApiData()
    .then(function(result) {      
        var acp = {};
        acp.resultdata = [ result ];      
        $scope.data = acp.resultdata;      
        $ionicLoading.hide();
   })

   $scope.search = function(data) {
        $scope.data = null;
        $scope.formData = {};
        $scope.formData.month = data.month;
        $scope.formData.origin  = data.origin;
        $ionicLoading.show({noBackdrop: false,template: '<p>Searching</p>'});        
        ApiAcpFactory.getApiData($scope.formData)
        .then(function(result) {             
            $scope.data = JSON.stringify(result);
            console.log(' scope.data '+$scope.data);      
            $ionicLoading.hide();
       })
        return $scope.data;
    }
})

The factory :

.factory('ApiAcpFactory', function($http, $q, ApiAcpEndpoint) { 
  var getApiData = function(data) {    
    var q = $q.defer();    
    $http.post(ApiAcpEndpoint.url,data)
    .success(function(data) {
        q.resolve(data);
    })
    .error(function(error){
        console.log('Had an error'+error)
        q.reject(error);
    })
    return q.promise;
  }
  return {
    getApiData: getApiData    
  };

})

Upvotes: 0

Views: 2290

Answers (1)

Alex Boisselle
Alex Boisselle

Reputation: 834

I'm pretty sure the reason is that your changes are happening within deferred callbacks. Therefore AngularJS is not noticing that turn happening in its cycle.

You say you tried $apply, can you post what you tried?

This would be the proper use in this situation:

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

This is all very nicely explained here.

Upvotes: 4

Related Questions