在 angularJS 控制器中使用 jQuery 的 $.ajax [英] Using jQuery's $.ajax within an angularJS controller

查看:33
本文介绍了在 angularJS 控制器中使用 jQuery 的 $.ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I use jQuery's $.ajax() function inside an angularJS controller (instead of angularJS built-in $http) so that the $scope values can be accessed from a view/template later?

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

I have this somewhat minimalistic angularJS controller:

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

在视图中类似:

<h1>Hello, {{ user.Username }}</h1>

但是,视图中的

在加载时将为空,尽管控制器中的 console.log() 告诉我 $scope.user按我的意愿填充.

However, the <h1> in the view will be empty on load, altough a console.log() in the controller tells me that $scope.user is populated just as I want.

现在,如果我用 $http.get() 替换 $.ajax() 调用,一切正常.

Now, If I replace the $.ajax() call with $http.get() everything works fine as expected.

我知道 $http 是 angularJS 内置的,但由于我不是从头开始,而是已经有很多代码在整个过程中使用 jQuery,我想坚持使用 jQuery 来获取 $.ajax().

I know of $http that is angularJS built-in, but since I am not starting from scratch but have already lots of code that uses jQuery throughout, I want to stick to jQuery for $.ajax().

有什么想法吗?

推荐答案

因为使用 jQuery ajax 超出了 angular 的世界,所以你需要将 $scope 赋值包裹在

Because using jQuery ajax is out of the world of angular, you need to wrap your $scope assignment inside of

$scope.$apply(function(){
    $scope.user = data;
});

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

Angular's $http comes pre-built with the digest cycle triggering mechanism.

这篇关于在 angularJS 控制器中使用 jQuery 的 $.ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆