Angularjs $ http VS jquery $ .ajax

lau*_*kok 14 javascript ajax jquery angularjs

我可以设置contextAngularjs $http,就像我们可以做到这一点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;
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

另外,jQuery中还有更多的回调$.ajax,比如.done,.promise我可以用它来操作context下面这样的,我想知道我是否可以这样做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"); 
    }
});
Run Code Online (Sandbox Code Playgroud)

Ram*_*ran 22

两者都是一样的

$ 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    
});
Run Code Online (Sandbox Code Playgroud)

但是 async: true,不受支持angular.js.

如果需要停止异步回调,那么必须使用$.ajax方式

更多细节请看这个讨论:从jquery $ .ajax到angular $ http

编辑:

如何显示隐藏 angular js

<div ng-show="IsShow">xx</div>



  $http.get('server.php').success(function(response) {
                $scope.contacts = response.data;
                $scope.IsShow=true;
                $scope.$apply();
            }).error(function(error)
        {
           $scope.IsShow=false; 
           $scope.$apply(); 
    });
Run Code Online (Sandbox Code Playgroud)

  • @lauthiamkok,是的,你可以做到jquery.那么为什么你使用angular.js?你可以使用jquery或angular.js来做到这一点.两者都是最好的.但angular.js有助于快速绑定jquery.快乐编码:) (2认同)

Jef*_*ard 3

只需使用Function.bind()您手上的函数来promise.then维护您想要的上下文。例如:

return $http({
    method: 'GET', 
    url:'server.php'
}).then(function(response) {
    $scope.contacts = response.data;
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

然而,我注意到你的回调都是操作元素——在 Angular 中你不需要做这些事情。是否有一些特定的事情是您想要执行但无法通过回调完成的?