如何使用Angular 1从$ templateCache加载图像

时间:2016-10-26 21:28:52

标签: angularjs angular-templatecache

我有一个plnkr,但故事很长,但归结为我需要能够使用templateCache中的图像。我尝试使用ng-src这样做...

=INDEX(A:E,MATCH(G2&"*",A:A,0)+2,5)

然而,这不起作用,我得到......

  

copy_icon':1 GET https://run.plnkr.co/ZyTH7LFhPLhdQpCI/'img / help / copy_icon'400()

所以它不是试图从templateCache中获取它。有没有办法做到这一点?

更新

我试过......

$templateCache.put('img/help/copy_icon', '://www.drupal.org/files/issues/sample_7.png')
...
template: '<img ng-src="{{url}}">'

但这不起作用

1 个答案:

答案 0 :(得分:1)

我不知道你试图通过使用$ templateCache来实现什么,在你的情况下只是将图像URL保存到缓存中,但我修改了你的代码,所以它显示了一个图像,我添加了控制器:

app.run(function($templateCache){
  $templateCache.put('img/help/copy_icon', 'http://www.drupal.org/files/issues/sample_7.png')
})

app.directive('ngImg', function(){
  return {
    rectrict: "E",
    scope: {
      url: "@url"
    },
    template: '<img ng-src="{{ imgUrl }}">',
    controller: function ($scope, $templateCache) {
      $scope.imgUrl = $templateCache.get($scope.url);
    }
  }
})

plunker:https://plnkr.co/edit/q5a9ptq8rd1G4uGkkNMe?p=preview

BTW,建议不要使用 ng 前缀作为自定义指令名称,并且应该为angular core directives / components保留