Angular.js 指令动态模板URL

编程入门 行业动态 更新时间:2024-10-26 10:29:26
本文介绍了Angular.js 指令动态模板URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在 routeProvider 模板中有一个自定义标签,它需要一个 directive 模板.version 属性将由范围填充,然后调用正确的模板.

I have a custom tag in a routeProvider template that that calls for a directive template. The version attribute will be populated by the scope which then calls for the right template.

<hymn ver="before-{{ week }}-{{ day }}"></hymn>

根据它是哪一周和哪一天,这首赞美诗有多个版本.我期待使用该指令来填充正确的 .html 部分.templateUrl 未读取该变量.

There are multiple versions of the hymn based on what week and day it is. I was anticipating to use the directive to populate the correct .html portion. The variable is not being read by the templateUrl.

emanuel.directive('hymn', function() {
    var contentUrl;
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            // concatenating the directory to the ver attr to select the correct excerpt for the day
            contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
        },
        // passing in contentUrl variable
        templateUrl: contentUrl
    }
});

摘录目录中有多个文件被标记为before-1-monday.htmlbefore-2-tuesday.html、……

There are multiple files in excerpts directory that are labeled before-1-monday.html, before-2-tuesday.html, …

推荐答案

您可以使用 ng-include 指令.

尝试这样的事情:

emanuel.directive('hymn', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.getContentUrl = function() {
                return 'content/excerpts/hymn-' + attrs.ver + '.html';
           }
       },
       template: '<div ng-include="getContentUrl()"></div>'
   }
});

更新.用于观看 ver 属性

UPD. for watching ver attribute

emanuel.directive('hymn', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
           attrs.$observe("ver",function(v){
               scope.contentUrl = 'content/excerpts/hymn-' + v + '.html';
           });
       },
       template: '<div ng-include="contentUrl"></div>'
   }
});

这篇关于Angular.js 指令动态模板URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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