【问题标题】:use $templateCache via script tag通过脚本标签使用 $templateCache
【发布时间】:2017-11-30 18:11:37
【问题描述】:

我将使用 $templateCache 脚本标签来显示我的 html 视图。 目前我有,

<body ng-app="myApp">
    <div ng-controller="myAppController">
    ....
    ....
    <div class="col-xs-12">
        <my-settings></my-settings>
    </div>

..
..
    </div>

还有我的 app.js,

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

myApp.config(['$httpProvider', function($httpProvider) {
 ....
 ....
}]);

myApp.controller('myAppController', ['$scope', '$http', '$rootScope', function ($scope, $http,$rootScope) {
//Other stuff
}

directive.js

'use strict';

angular.module('editor').directive("my-settings", function() {
    return {
        templateUrl: '/views/templateId.html'
    };
});

我想通过脚本标签或作为服务使用 $templateCache。但是通过服务添加它时,我必须将我所有的 html 元素放在 $templateCache.put() 中。

var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});

现在我想,我会改用脚本标签。

<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>

根据文档,它必须是 $rootElement 的后代。那么我必须将脚本放在哪里。这会包含在同一文件本身的&lt;body ng-app="myApp"&gt; 中吗?

【问题讨论】:

    标签: angularjs angular-templatecache


    【解决方案1】:

    在定义指令名称时需要使用驼峰式大小写:

    .directive("mySettings" ...
    

    此外,您可以在与指令相同的范围内定义内联模板,如下所示:

    <div ng-controller="myAppController">
        ....
        ....
        <div class="col-xs-12">
            <my-settings></my-settings>
        </div>
    
    ..
    ..
        <script type="text/ng-template" id="templateId.html">
          <p>This is the content of the template</p>
        </script>
      </div>
    

    只要确保内联模板的 ID 与 templateUrl 匹配即可。您可以查看一个工作小提琴here。

    【讨论】:

    • 谢谢..我会检查..另外我有多个脚本。那么我可以将所有内容放在主html文件之外的某个文件中吗?那我怎么打电话呢?
    • @ep -- templateUrl 必须是有效的模板标识符。它可以是内联模板的 ID,也可以是 http URL。 AngularJS 通常会自动获取内容并将其存储在$templateCache 中。
    • 还有一个问题:如果我有 .. 我应该保持脚本不变吗?
    猜你喜欢
    • 2010-12-20
    • 2012-11-11
    • 1970-01-01
    • 2014-10-15
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多