Joey Hipolito
Joey Hipolito

Reputation: 3166

Angular equivalent of .done in jquery

I cannot find an alternative solution to what I am trying to do, lets say I have this code in jquery:

$.get 'file.json', (re) ->
   for k, v in re
      tpl = "<div>{{v.content}}</div>";
      $ '#container'.append tpl
 .done () ->
     impress().init()

That works fine because, .done executes the code only after the ajax, but angular seems like don't have some like .done, and impress().init() cannot reinitialize when the content was loaded, therefore there will be a mistake on data binding..

Here is my attempt on angular

App.controller 'SomeCtrl', ($scope, $http) ->
   $http.get('file.json')
   .success (res) ->
      $scope.slides = res
   #what could possibly be in here

Upvotes: 1

Views: 318

Answers (3)

dumbledad
dumbledad

Reputation: 17527

Looking a similar question, in one of the answers Benjamin Gruenbaum suggests using .always which is provided on all promises (including the return value from $http.get). He includes a useful code example on fiddle:

HTML:

<div ng-controller="Ctrl">
  {{data}}
</div>

JavaScript:

var myApp = angular.module('myApp', []);
var data = {hello:"World!"};
function Ctrl($scope, $http) {
    $http.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }).always(function(data) {
         alert("HI");  
    });
}

Benjamin notes that .always has been superseded by .finally. Here's a fiddle using .finally and the latest Angular.js.

HTML:

<div ng-controller="MyCtrl">Hello, {{name}}!</div>

JavaScript:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.name = 'Superhero';
    $http.get('/echo/json/').
    success(function() {
        $scope.name = 'Sidekick';
        }).  
    finally(function() {
         alert($scope.name);  
    });
}]);

(N.B. Here's the documentation, and nfiniteloop's answer to $q 'finally' not working in IE8 may also be useful.)

Upvotes: 1

Michael Benford
Michael Benford

Reputation: 14114

You can call then after success:

$http.get('file.json')
  .success(function(data) {
    console.log('success');
  })
  .then(function() {
    console.log('success again');
  });

Here's an example.

Upvotes: 2

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

Angularjs has methods for success and error. Read the documentation

 $http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Upvotes: 1

Related Questions