Angular.js 指令动态模板URL [英] Angular.js directive dynamic templateURL

查看:29
本文介绍了Angular.js 指令动态模板URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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屋!

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