Angularjs templateUrl 无法在 ng-repeat 中绑定属性 [英] Angularjs templateUrl fails to bind attributes inside ng-repeat

查看:27
本文介绍了Angularjs templateUrl 无法在 ng-repeat 中绑定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用指令来显示 html 片段.

以及指令中的 templateUrl,能够包含片段作为 html 文件.

指令不起作用,如果我尝试调用在内置的 ng-repeat 指令中({{snip}} 按原样传递,没有替代):

div ng-repeat="snip in ['snippet1.html','snippet2.html']"><my-template snippet="{{snip}}"></my-template>

作为参考,这里是指令:

app.directive("myTemplate", function() {返回 {限制:'EA',替换:真的,范围:{片段:'@'},模板网址:功能(元素,属性){console.log('我们尝试加载以下代码片段:' + attrs.snippet);返回 attrs.snippet;}};});

还有一个 plunker 演示.

非常感谢任何指针.(指令在我的代码中更复杂,我试图得到一个最小的例子,其中问题是可重现的.)

解决方案

attrs 用于 templateUrl 的参数在指令执行期间未插入.您可以使用以下方式来实现这一点

app.directive("myTemplate", function() {返回 {限制:'EA',替换:假,范围:{片段:'@'},模板:'<div ng-include="snippet"></div>'};});

演示:http://plnkr.co/edit/2ofO6m45Apmq7kbYWJBG?p=preview

I'm using directive to display html snippets.

And templateUrl inside the directive, to be able to include snippets as html file.

The directive does not work, if I try to call inside a builtin ng-repeat directive ({{snip}} is passed as is, without substitute):

div ng-repeat="snip in ['snippet1.html','snippet2.html']">
  <my-template snippet="{{snip}}"></my-template>
</div>

For reference, here is the directive:

app.directive("myTemplate", function() {
return {
    restrict: 'EA',
    replace: true,
    scope: { snippet: '@'},
    templateUrl: function(elem, attrs) {
      console.log('We try to load the following snippet:' + attrs.snippet);
      return attrs.snippet;
    }
  };
});

And also a plunker demo.

Any pointer is much appreciated. (the directive is more complicated in my code, I tried to get a minimal example, where the issue is reproducible.)

解决方案

attrs param for templateUrl is not interpolated during directive execution. You may use the following way to achieve this

app.directive("myTemplate", function() {
  return {
    restrict: 'EA',
    replace: false,
    scope: { snippet: '@'},
    template: '<div ng-include="snippet"></div>'
  };
}); 

Demo: http://plnkr.co/edit/2ofO6m45Apmq7kbYWJBG?p=preview

这篇关于Angularjs templateUrl 无法在 ng-repeat 中绑定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆