在angularJS控制器中使用jQuery的$ .ajax

Dyn*_*lon 10 ajax model-view-controller jquery angularjs

如何在angularJS控制器(而不是angularJS内置$ http)中使用jQuery的$ .ajax()函数,以便以后可以从视图/模板访问$ scope值?

我有这个有点简约的angularJS控制器:

function UserCtrl($scope, $http) {
    $.ajax('http://localhost:8080/admin/user/johndoe').success(function(data) {
        $scope.user = data;
    });
}
Run Code Online (Sandbox Code Playgroud)

在视图中,例如:

<h1>Hello, {{ user.Username }}</h1>
Run Code Online (Sandbox Code Playgroud)

但是,<h1>视图中的视图在加载时将为空,尽管console.log()控制器中的a告诉我$ scope.user是按我的意愿填充的.

现在,如果我$.ajax()$http.get()一切正常工作替换呼叫.

我知道$http这是angularJS内置的,但由于我不是从头开始但已经有很多代码使用jQuery,我想坚持使用jQuery for $ .ajax().

有任何想法吗?

Sha*_*.io 23

因为使用jQuery ajax是在angular的世界之外,你需要将$ scope赋值包装在其中

$scope.$apply(function(){
    $scope.user = data;
});
Run Code Online (Sandbox Code Playgroud)

Angular的$ http预先构建了摘要周期触发机制.