为什么templateCache不能在angular js中工作

why templateCache not working in angular js?

本文关键字:js 工作 angular templateCache 不能 为什么      更新时间:2023-09-26

我正在尝试使用$templateCache。但当我使用$templateCache.get()进行控制台操作时,它会给我未定义的结果。。为什么?

http://plnkr.co/edit/MAXQmzTVR8fpsw645rct?p=preview

<script>
      angular.module('app',[ ]).directive('h',function($templateCache){
        console.log($templateCache.get('about.html'))
        var element=angular.element('<input type="text" ng-model="message"><div>{{message}}</div>');
       return { restrict:'E',
        scope:{},
        templateUrl:'a.html',replace:true,
        transclude:true,
        compile:function(tElement){
          tElement.append(element);
          return function(s,e,a){
            s.$watch('message',function(val){
             // console.log('------'+val)
            })
          }
        }

       }
      })
    </script>

        **console.log($templateCache.get('about.html'))** give me undefined why ?

因为当前您正在注册该指令的同时运行该语句。那一次$templateCache中没有模板。您需要将该行放入指令compile函数中,然后只有您才能在其中获得数据。

看到这个问题,我认为这应该会帮助你

Angular Tabs渲染具有缓存的模板;ng包含src";

模板被加载到模板缓存中,以便快速检索。您可以通过$templateCache服务直接加载模板。

angular.module('app', []).run(function($templateCache) {
  $templateCache.put('a.html');
});

要检索,只需在HTML 中使用它

<div ng-include=" 'a.html' "></div>

$templateCache.get('a.html')