Angularjs $ http VS jquery $ .ajax
我可以在Angularjs $http
设置context
,就像我们可以在jQuery's $.ajax
吗?
define([ 'app' ], function(app) { app.controller("controller1", function($scope, $route, $http) { return $http({ method: 'GET', url: 'server.php' }).then(function(response) { $scope.contacts = response.data; }); }); });
另外,jQuery的$.ajax
还有更多的回调,比如.done
, .promise
,我可以用它来操作下面的context
,我想知道我是否可以在Angularjs
做同样的Angularjs
?
$.ajax({ type: "GET", dataType: "HTML", url: 'server.php', context: $("#container"), async: true, beforeSend: function() { $(this).html('loading...'); }, success: function (returndata, status, jqxhr) { $(this).html(returndata).hide().fadeIn(); }, }).fail(function() { alert("error"); }).done(function(returndata) { }, .always(function() { alert("complete"); } });
两者都是一样的
$ http是从angular.js脚本引用的
$ .ajax是从jquery脚本引用的
-
和$ http不支持
async:false
-
$ .ajax支持
async:false
您可以通过这种方式使用angular.js
来实现
$http.get('server.php').success(function(response) { $scope.contacts = response.data; }).error(function(error) { //some code });
但是async: true,
在angular.js
中angular.js
。
如果需要停止异步回调,那么必须使用$.ajax
方式
更多细节请看这个讨论: 从jquery $ .ajax到angular $ http
编辑:
如何在angular js
显示隐藏
xx $http.get('server.php').success(function(response) { $scope.contacts = response.data; $scope.IsShow=true; $scope.$apply(); }).error(function(error) { $scope.IsShow=false; $scope.$apply(); });
只需对你手边的函数使用Function.bind()
,然后保持你想要的上下文。 例如:
return $http({ method: 'GET', url:'server.php' }).then(function(response) { $scope.contacts = response.data; }.bind(this));
但是,我注意到你的回调都是操纵元素 – 你不需要在Angular中做的事情。 是否有某些特定的东西你想要做但却无法回调?