我正在使用以下代码片段从服务器获取数据以加载页面的初始内容。
(function () {
'use strict';
angular
.module('app')
.controller('MyController', MyController);
MyController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function MyController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {
/*Discussion Board related Functions*/
angular.element(document).ready(function () {
// Get Current User
$rootScope.globals = $cookieStore.get('globals') || {};
$scope.currentUser = AuthenticationService.GetAuthData($rootScope.globals.currentUser.authdata);
$.getJSON(
"http://localhost/getSomeServerData.php",
{ userName: $scope.currentUser },
$scope.getSomeDataResponse
);
});
$scope.getSomeDataResponse = function (jason) {
var servRet = jason;
alert("On Load Called-2");
};
}
})();
但是,响应函数 $scope.getSomeDataResponse 没有被调用。
请告诉我这种方法有什么问题。
最佳答案
However, the response function $scope.getSomeDataResponse is not getting called.
Please let me know what is wrong with this approach.
问题是,您在声明 getSomeDataResponse 之前引用它。此外,您正在使用 jQuery 的 getJSON()
在您的 angularJS 代码中使用 HTTP GET 请求从服务器获取数据。
这不是特别推荐的做法。如果您在页面中包含 jQuery,AngularJS 将在指令中包装元素时使用 jQuery 而不是 jqLite,否则它将委托(delegate)给 jqLite(这可能并非在所有情况下都有效)。为了安全起见,请使用 Angular 的 $http.get()
服务而不是 $.getJSON()
$http.get("http://localhost/getSomeServerData.php",{ userName: $scope.currentUser})
.then(function(jason){
//success handler function
var servRet = jason;
alert("On Load Called-2");
},function(err){
//error handler function
alert(err);
})
当然,您需要在 Controller 中注入(inject) $http
服务才能使其正常工作。看看this其他可能的替代方案的线程。
干杯!
关于javascript - $.getJSON 从 angular.element(document).ready 或 initController 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682157/