在AngularJS中使用内联模板

Ody*_*Ody 81 javascript angularjs

我想加载内联视图模板.

我将模板包装在类型的脚本标记中text/ng-template,并将id设置为temp1.html.这是我的模块配置的样子

learningApp.config(function ($routeProvider) {
    $routeProvider
        .when("/first",{ controller: "SimpleController", templateUrl: "temp1.html"})
        .when("/second", {controller: "SimpleController", templateUrl: "temp2.html"})
        .otherwise({redirectTo : "/first"});
});
Run Code Online (Sandbox Code Playgroud)

它告诉我GET http://localhost:41685/temp1.html 404 (Not Found)在我的控制台窗口中意味着它正在寻找该名称的文件.

我的问题是:如何配置我的路由以使用内联模板?

更新:这是我的服务器呈现的DOM的样子

<!DOCTYPE html>
<html>
<head>
    <script src="/Scripts/angular.js"></script>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
</head>
<body>
    <div class="container">       
    <h2>Getting Started with Angular</h2>
    <div class="row">
        <div class="panel" ng-app="LearningApp">
            <div ng-view></div>
        </div>
    </div>

<script type="text/ng-template" id="temp1.html">
    <div class="view">
        <h2>First View</h2>
        <p>
            Search:<input type="text" ng-model="filterText" />
        </p>
        <ul class="nav nav-pills">
            <li ng-repeat="cust in customers | orderBy:'name' | filter: filterText "><a href="#">{{cust.name}} - {{cust.school}}</a></li>
        </ul>
    </div>
</script>

<script type="text/ng-template" id="temp2.html">
    <div class="view">
        <h2>Second View</h2>
        <p>
           Search:<input type="text" ng-model="filterText" />
        </p>
        <ul class="nav nav-pills">
            <li ng-repeat="cust in customers | orderBy:'name' | filter: filterText "><a href= "#">{{cust.name}} - {{cust.school}}</a></li>
        </ul>
    </div>
</script>
    </div>
    <script src="/Scripts/jquery-1.9.1.js"></script>
    <script src="/Scripts/bootstrap.js"></script>
    <script src="/Scripts/app/LearningApp.js"></script>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

pko*_*rce 111

哦,你是在正确的轨道上,唯一的问题是标签是ng-app使用该指令的DOM元素之外.如果将其移动到<body ng-app="LearningApp">元素内联模板应该工作.

您可能还会发现这个问题是相关的:有没有办法让AngularJS在开始时加载部分,而不是在需要时?

  • 这是文档必须提到的.我想知道为什么那些404出现了...... (3认同)
  • 我现在明白为什么大多数教程都喜欢将ng-app指令添加到html元素中.这是因为与该app/module相关的任何内容都必须在ng-app范围内,因此将其放在html标记中可以避免将来出现这样的问题 (2认同)

tsc*_*ela 31

尝试使用脚本元素的id-Attribute来设置应该工作的模板的名称.

<script type="text/ng-template" id="temp1.html">
   ... some template stuff
</script>
Run Code Online (Sandbox Code Playgroud)