如果您想要创建专门用于AJAX调用的对象,那么您应该查看AngularJS services。服务是可以注入控制器,其他服务和指令的对象,它们通常提供某种可重用的功能(在你的情况下它会提供AJAX功能)。
控制器的目的是提供与视图交互的逻辑。如果你正在创建一个不以某种方式与视图交互的控制器,那么你做错了什么。
你的AJAX服务可能是这个样子:
<script>
var myApp = angular.module('myApp', [])
// notice the inclusion of 'myAjax' here. This is where we are injecting our
// custom service that me made.
.controller('MyController', ['$scope', 'myAjax', function ($scope, myAjax) {
$scope.url = 'cutepuppies.com';
$scope.params = {
cutenessLevel: 'extraCute'
};
function successcb(data, status, headers, config) {
//something on success
}
function failure(data, status, headers, config) {
//something on failure
}
$scope.get = function() {
// This is where we use our service to make an ajax call!
// We also pass in 2 callbacks, one to be called on success and one on error
myAjax.get($scope.url, $scope.params, successcb, failurecb);
}
}]);
// Here we define our service. This is what we will use in our app to make ajax calls.
myApp.service('myAjax', ['$http', function ($http) {
return {
get: function (url, params, successcb, failurecb) {
$http.get({
method: 'GET',
url: url,
params: params
})
.success(successcb)
.error(failurecb);
}
}
});
</script>
下面就以供参考$ HTTP服务的链接:https://docs.angularjs.org/api/ng/service/$http
来源
2014-05-05 23:31:28
pje
如果你想使用的角度为是使一个Ajax调用,那么你为什么使用角? Angular很好地处理了很多事情,但是对于ajax调用,图书馆大小的代价似乎并不合理,您能解释一下吗? – Brocco
是的,我知道。但我也知道,将来我不仅可以在我的项目中使用ajax调用。所以这只是第一步。我只是想知道是否可以将控制器附加到我的视图中,而无需在我的HTML中指出它。因为如果我已经在我的JS中指出了它,那么为什么我需要另外告诉HTML。你看我的观点。 – o1egon