gpt4 book ai didi

jquery - 在 angularJS Controller 中使用 jQuery 的 $.ajax

转载 作者:行者123 更新时间:2023-12-03 22:20:08 25 4
gpt4 key购买 nike

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

我有这个有点简约的 angularJS Controller :

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

在 View 中类似:

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

但是,<h1>加载时 View 中将为空,尽管 console.log() Controller 中的内容告诉我 $scope.user 已按照我的意愿填充。

现在,如果我替换 $.ajax()调用 $http.get()一切都按预期正常工作。

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

有什么想法吗?

最佳答案

因为使用 jQuery ajax 超出了 Angular 的范围,所以您需要将 $scope 赋值包装在

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

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

关于jquery - 在 angularJS Controller 中使用 jQuery 的 $.ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com