【问题标题】:AngularJS - preloaded templates not working with directiveAngularJS - 预加载的模板不适用于指令
【发布时间】:2014-03-01 10:53:31
【问题描述】:

我想将我所有的模板放在脚本标签中,并从我的指令中使用它们,而不需要使用 ajax 请求。

这是我的模板:

<script id="article_row.html" type="text/ng-template">
    <tr>
        <td class="article-id">[[ article.id ]]</td>
        <td>[[ article.title ]]</td>
        <td>[[ article.user_id ]]</td>
        <td>[[ article.created_at ]]</td>
        <td>
            <article-restore id="article.id"></article-restore>
        </td>
    </tr>
</script>

这是我的指令:

app.directive("articleLine", [function(){

    return {

        return: 'E',
        scope: {
            article : "=data"
        },
        templateUrl: "article_row.html"

    };

}]);

加载时,我在控制台中收到此错误:

Error: Failed to load template: article_row.html

我在控制台中看到浏览器正试图从http://localhost/articles/article_row.html 获取它 而是在页面中查找它,是我做错了什么吗?

谢谢!

【问题讨论】:

  • 请提供一个小提琴/plunker。没有看到代码的第一个猜测是您的带有模板的&lt;script&gt;标签在ng-app之外,但这只是一个猜测。
  • 它在 ng-app 内,在尝试了一个小时让它工作后,我刚刚将它移到我在页面中使用指令的地方上方并且它工作正常(两个地方都在里面ng-app),猜猜为什么会这样?
  • 这是因为您在 angular 有机会加载模板之前尝试使用该指令。在调用指令之前必须加载模板。

标签: javascript angularjs angularjs-directive angular-template


【解决方案1】:
<article-line data="myData"></article-line>

当您将articelLine 指令放在上面时,将在您包含article_row.html ng-template 并收到错误之前编译此行。

所以,你必须在它前面加上ng-template

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2020-09-01
    相关资源
    最近更新 更多