本文介绍了AngularJs无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的index.html页面将导致一个无限循环。要重现:

The following index.html page causes an infinite loop. To reproduce:


  1. 下载(本地或远程)Web服务器上以下链接GitHub的项目(我曾试图在plunker和无限循环并没有发生)

  2. 从浏览器请求它。

  3. 点击页面上的P1P2链接。

无限循环开始。在服务器端,日志产生

The infinite loop starts. On the server side, the log produces:

server request for * handled
GET /p1/p2 304 8ms
server request for * handled
GET /p1/partials/template1 304 4ms

/谐音/ template1的这里前注意 / P1 。哪里是从何而来?这导致了无限循环,因为AngularJS找不到此网址上的模板,并进入循环结果。这缩短 / P1 / P2 AngularJS为 / P1 路线某种程度上消除了该问题。

Note the /p1 in front of /partials/template1 here. Where did that come from? That is causing the infinite loop because AngularJS cannot find the template at this url and enters the loop as a result. Shortening this /p1/p2 AngularJS route to /p1 eliminates the problem somehow.

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <script>document.write('<base href="' + document.location + '" />');</script>
  </head>
  <body ng-app="minimalApp">
    <p>Index Page That Contains ng-view below..</p>
    <div ng-view></div>
    <p><a ng-href="p1/p2">p1p2</p>
    <p><a ng-href="#">#</p>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
    <script>
      'use strict';
      var minimalApp = angular.module('minimalApp', []).
        config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
          $routeProvider.
            when('/', {
              templateUrl: 'partials/template1',
              controller: IndexCtrl
            }).
            when('/p1/p2', {
              templateUrl: 'partials/template2',
               controller: T2Ctrl
            }).
            otherwise({
              redirectTo: '/'
            });

          $locationProvider.html5Mode(true);
        }]);

      function IndexCtrl($scope) {
      }

      function T2Ctrl($scope) {
      }
    </script>
  </body>
</html>

(我把HTML这里容易让即使是通过玉创建的模板)

(I put the html here to make it easy even though the templates are created via jade)

我用的服务器是节点/ EX preSS。完整的项目在GitHub上。

The server I used is node/express. The complete project is on github here.

和内嵌模板相同的HTML页面和工作原理是。

And the same html page with the templates embedded and that works is here.

推荐答案

的谐音/ template1的'是相对于你在哪里,所以当从'/ P1 / P2'调用,浏览器假定您在目录/ P1'并从那里建立的路径。

'partials/template1' is relative to where you are, so when called from '/p1/p2', the browser assumes you are in the directory '/p1' and builds the path from there.

如果您添加preceding斜线,如/谐音/ template1的',这将始终建立在Web服务器根目录的路径。

If you add the preceding slash, as in '/partials/template1' this will always build the path from the webservers root directory.

这篇关于AngularJs无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:28