json - AngularJS 在 Controller 中多次调用 HTTP

标签 json http angularjs

我正在使用 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 调用都会被调用两次。这是标准行为吗?

非常感谢,

破折号

enter image description here

最佳答案

此问题也可能是由于 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/

相关文章:

php - 无法让 Composer "path"存储库工作

asp.net - 404.17 错误 - 请求的内容似乎是脚本

c# - 在 Visual Studio 中显示不友好的 HTTP 500 错误

c - Arduino 程序资源不足

javascript - AngularJS 上的 Blazy

javascript - Angularjs指令如何检测属性的变化

javascript - 从脚本标签使用 Json 键时未定义

c# - 将对象从大型 JSON 文件转换为 .NET 中对象的最快方法

ios - json数据自定义http请求

javascript - 清除 angularjs 表单中的错误