$ rootScope:infdig angularjs中的错误

时间:2017-05-29 19:13:33

标签: javascript html angularjs

我正在使用AngularJS制作应用程序。

突然间我收到了这个错误。

  

错误:[$ rootScope:infdig] http://errors.angularjs.org/1.6.4/ $ rootScope / infdig?p0 = 10& p1 =%5B%5D

请参阅我的代码:

HTML:

<body ng-app="invApp" ng-controller="InvoiceController as ctrl">
<span ng-repeat="code in ctrl.codes">{{ getProduct(code) }}</span>
</body>

JS:

var app = angular.module("invApp", []);
app.controller("InvoiceController", function ($scope, $http) {
    $scope.codes = ["KKS", "KKB", "SNS"];
    $scope.getProduct = function (code) {
        $http({
            method: 'GET',
            url: '../api?action=getproduct&code='+code
        }).then(function successCallback(response) {
            var something = response.data;
        });
        return something;
    };
});

4 个答案:

答案 0 :(得分:1)

这个

 <body ng-app="invApp" ng-controller="InvoiceController">
 {{ getProduct("KKS") }}
 </body>

将创建不确定数量的请求。为了帮助你,我需要你想要做什么?

答案 1 :(得分:0)

当你在{{function()}}中调用一个函数时,你需要小心。插值运行每个摘要周期,并且您正在调用其中的函数,问题是您正在进行$ http调用,这再次触发摘要周期。尝试直接从控制器调用它。在页面加载并使用此数据时,您应该进行一次http调用。

<body ng-app="invApp" ng-controller="InvoiceController as ctrl">
    <span ng-repeat="p in products">{{ p }}</span>
</body>

app.controller("InvoiceController", function ($scope, $http) {
    $scope.getProducts("all your codes");
    $scope.getProducts = function (codes) {
        $http({
            method: 'GET',
            url: '../api?action=getproducts'
        }).then(function successCallback(response) {
            $scope.products = response.data;
        });
    };
});

让您的服务器立即返回包含所有产品(getProducts而不是getProduct)的数组,然后使用ng-repeat迭代它。 它应该看起来像那样。

答案 2 :(得分:0)

  

当应用程序的模型变得不稳定时会发生此错误   每个$摘要周期触发状态更改和后续$摘要   周期。 AngularJS检测到这种情况并阻止无限循环   导致浏览器无响应。

通过服务器调用呈现数据是一种不好的做法。因为angularjs生命周期每次都会调用服务器。

以下是我将如何实现它:

 var app = angular.module("invApp", []);
 app.controller("InvoiceController", function ($scope, $http) {
     $scope.getProduct = function (code) {
         $http({
             method: 'GET',
             url: '../api?action=getproduct&code='+code
         }).then(function successCallback(response) {
             $scope.product = response.data;
         });
    }; 
});

$scope.getProduct('KKS');

在模板中使用范围内保存的产品。

<body ng-app="invApp" ng-controller="InvoiceController">
 {{ product }}
</body>

答案 3 :(得分:0)

您的代码中几乎没有问题。

something的回归是错误的;您正尝试从执行异步调用的方法返回

您应该做的是在加载后立即添加$scope获取的数据,因此:

$scope.codes = ['KKS', 'KKB', 'SNS'];

$scope.getProduct = function (code) {
  return $http({
    method: 'GET',
    url: '../api?action=getproduct&code=' + code,
  });
};

$q
  .all($scope.codes.map(function (code) {
    return $scope.getProduct(code);
  }))
  .then(function (products) {
    $scope.products = products;
  });

然后:

<body ng-app="invApp" ng-controller="InvoiceController as ctrl">
  <span ng-repeat="product in ctrl.products">{{ product }}</span>
</body>