动态templateUrl在指令中基于元素属性插值

时间:2016-02-27 05:55:42

标签: angularjs angularjs-directive

我有一个html元素,如下所示:

.spec_iframe {
        width: 100%;
        overflow: hidden;
    }

我希望我的指令使用不同的<new-element data-type="{{widget.type}}"></new-element> ,具体取决于templateUrl的内容。

type

始终返回的模板为appDirectives.directive('newElement', function() { return { restrict : 'E', scope: false, templateUrl: function(elem, attrs) { var template_url = (attrs.type == 'widgetA') ? 'template-a.html' : 'template-other.html'; return template_url; } } }); ,因为template-other.html值仍为type且尚未进行插值。

是否可以通过某种方式对{{widget.type}}属性进行监视并相应更改模板?

1 个答案:

答案 0 :(得分:1)

你做不到:

var template_url = (attrs.type == 'widgetA') ? 'template-a.html' : 'template-other.html';

因为您无法访问模板方法中的指令属性,但您可以执行以下操作:

appDirectives.directive('newElement', function() {          
    return {
        restrict : 'E',
        scope: {},
        bindToController: {
         type: '='
        },
        controller: 'SomeController',
        controllerAs: 'ctrl',
        template: '<div ng-if="ctrl.type === 'widgetA'"><!-- your widgetA contet --></div><div ng-if="ctrl.type === 'widgetB'"><!-- your widgetB content --></div>';
    }
});

在这里你可以找到一篇关于如何用链接功能做你想做的事情的文章,但我建议改用控制器。

http://onehungrymind.com/angularjs-dynamic-templates/