我正在使用 Angular 开发一个页面,并且在我的 Controller 中有一个 init() 方法。代码如下:
var filtersController = ['$scope', '$http', function ($scope, $http) {
$scope.init = function () {
$http({
method: 'GET',
url: '/json-tags-test',
cache: true
}).success(function (data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
}];
这只是对一个简单的 JSON 文件的调用。
我的HTML如下:
<div class="container main-frame" ng-app="projectsApp" ng-controller="filtersController" ng-init="init()">
</div>
出于某种原因,每次我加载页面时,此 get 调用都会被调用两次。这是标准行为吗?
非常感谢,
破折号
最佳答案
此问题也可能是由于 ng-app
路由到您的 Controller 和页面中的 ng-controller
引用引起的。例如,如果您的应用看起来像:
<html lang="en" ng-app="myApp">
<head>...</head>
<body>
<div ng-controller="myController">
...
</div>
</body>
</html>
定义应用程序的 Javascript:
angular.module('myApp',[]) {
$routeProvider.when('/path', {templateUrl: '...', controller: myController);
在上面的例子中,通过定义到 myController 的路由, Controller 将被实例化两次,您将看到两次调用,如前所述。
已更新
上面的代码描述了问题所在,但缺少正确的解决方案,所以我根据@Intrepid 评论更新了答案。
如果您已经在路由中定义,需要从您的 html 模板中删除 ng-controller="myController"
。
关于json - AngularJS 在 Controller 中多次调用 HTTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17967437/