【问题标题】:Using templateUrl in directive freezes app在指令中使用 templateUrl 会冻结应用程序
【发布时间】:2014-11-24 19:23:06
【问题描述】:

我有一个 MEANstack 应用程序,它的行为非常奇怪。 使用 templateUrl 创建指令会冻结应用程序。相同的指令仅使用带有模板的 html 代码。

dashboard.html:

 <h3>Recent</h3>
 <div my-callout></div>

dashboard.controller.js:

.directive('myCallout', function(){
    return {

    templateUrl:'myCallout.html'
};
})

myCallout.html:

<div>
    <p>fdsfs</p>
</div>

这行得通:

.directive('myCallout', function(){
    return {

    template:' <p> mhgfhut </p>'
    };
})

;

【问题讨论】:

  • 可能找不到您的myCallout.html?您是否正确引用它??
  • 我敢肯定。将其更改为此后,我收到一条警告:“尝试多次加载 Angular”,它只是进入了这个疯狂的无限循环,不断发出所有 XHR 请求
  • 可能存在无限循环,请检查您的 html 页面中是否没有调用您创建的相同指令,在您的情况下,您不应在 myCallout.html 内调用 myCallout directive

标签: javascript angularjs angularjs-directive mean-stack


【解决方案1】:

你的指令对我来说很好:

~/angular_js_projects/9app$ tree
.
├── app.css
├── app.js
├── bootstrap
      <snip>
├── index.html
└── myCallout.html

app.js:

var app = angular.module('myApp', []);

app.directive('myCallout', function() {
  return {
    templateUrl: 'myCallout.html'
  }
});

myCallout.html:

<div>myCallout.html</div>

index.html:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
  <title>AngularJS</title>

  <meta charset="UTF-8">  <!-- For html5 (default is UTF-8) -->
  <meta name="viewport" content="width=device-width, initial-scale=1">  <!-- For Bootstrap -->

  <!-- Bootstrap CSS with glyphicon fonts in bootstrap/fonts/ -->
  <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
  </head>

<body>

  <h3>Recent</h3>
  <div my-callout></div>

<!-- Angular -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<!-- App Script -->
<script src="app.js"></script>
</body>
</html>

使用这个目录结构:

~/angular_js_projects/9app$ tree
.
├── app.css
├── app.js
├── bootstrap
      <snip>
├── index.html
└── templates
    └── myCallout.html

那么 app.js 看起来像这样:

var app = angular.module('myApp', []);

app.directive('myCallout', function() {
  return {
    templateUrl: 'templates/myCallout.html'
  }
});

【讨论】:

  • 我的结构有点复杂,但引用似乎不是问题。我收到一个警告,一个带有 XHR 请求的无限循环,然后是一个像这样开始的错误:“错误:[$rootScope:infdig] 10 $digest() 达到了迭代。中止!(...)”
猜你喜欢
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多