jquery中.done的角度等价物
我无法找到我想要做的替代解决方案,让我说我在jquery中有这个代码:
$.get 'file.json', (re) -> for k, v in re tpl = "{{v.content}}"; $ '#container'.append tpl .done () -> impress().init()
这样工作正常,因为.done
只在ajax之后执行代码,但angular似乎没有像.done
,并且impress().init()
在内容加载时无法重新初始化,因此会出现错误关于数据绑定..
这是我对角度的尝试
App.controller 'SomeCtrl', ($scope, $http) -> $http.get('file.json') .success (res) -> $scope.slides = res #what could possibly be in here
success
后你可以打电话:
$http.get('file.json') .success(function(data) { console.log('success'); }) .then(function() { console.log('success again'); });
这是一个例子 。
Angularjs有success
和error
方法。 阅读文档
$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. });
看一个类似的问题 ,在其中一个答案中, Benjamin Gruenbaum建议使用所有承诺上提供的.always
(包括来自$http.get
的返回值)。 他在小提琴上包含了一个有用的代码示例 :
HTML:
{{data}}
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"); }); }
本杰明指出, .always
被.finally
取代。 这是一个使用.finally
和最新的Angular.js 的小提琴 。
HTML:
Hello, {{name}}!
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); }); }]);
(NB这里是文档 , nfiniteloop对$ q 的回答 ‘最终’在IE8中不起作用也可能有用。)