Angularjs templateUrl 无法在 ng

编程入门 行业动态 更新时间:2024-10-05 17:28:47
本文介绍了Angularjs templateUrl 无法在 ng-repeat 中绑定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用指令来显示 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 18:51:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1007889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Angularjs   templateUrl   ng

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!