问题
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
回答1:
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.
回答2:
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.
});
回答3:
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.)
来源:https://stackoverflow.com/questions/18755085/angular-equivalent-of-done-in-jquery