使用jQuery的$。阿贾克斯内的angularJS控制器 [英] Using jQuery's $.ajax within an angularJS controller

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

问题描述

如何使用jQuery的$就()函数的angularJS控制器内(而不是angularJS内置$ http)进行,以使$范围值可以从一个视图/模板以后访问?

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>

不过,&LT; H1&GT; 视图将是空的负载,altough一个的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()一切正常调用细如预期。

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

我知道 $ HTTP 是内置angularJS的,但因为我不是从头开始,但已经很多,在整个使用jQuery的code,我要坚持的jQuery的$。阿贾克斯()。

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是出棱角分明的世界,你需要用里面的$范围分配

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;
});

角的$ HTTP来pre-内置了与消化周期触发机制。

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

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

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