3

我想要使用$ templateCache.But当我使用$ templateCache.get()时,它给我一个未定义的..why?为什么templateCache不能在角js中工作?

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 ? 
+0

首先,尝试格式化你的代码:)。 –

+1

首先你应该在执行'$ templateCache.get('about.html')'之前''templateCache.put('about.html','

')'',在你的例子中,其中的about.html是? –

回答

1

因为当前正在运行的声明,而注册该指令。那个时间$templateCache没有模板。 您需要将该行放入指令compile函数中,然后只有您将获取其中的数据。

+0

你可以请给暴徒吗? –

+0

明白了..我明白了 –

0

看到这个问题,我想这应该帮助你

Angular Tabs render templates with caching in "ng-include src"

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

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

要检索简单地用它在你的HTML

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

$templateCache.get('a.html')