AngularJS指令中的动态模板(非templatUrl)

时间:2013-09-20 20:11:10

标签: angularjs angularjs-directive

我已经看到了在Angular中的指令中拥有动态templateUrl的能力,但在研究时我还没有看到动态模板。

.directive('col', function () {
    var template = '<div class="one" ng-transclude></div>';
    return {
        restrict: 'E',
        scope: {},
        transclude: true,
        replace: true,
        template: template,
        link: function (scope, ele, attrs) {
            if (attrs.two !== undefined) {
                template = '<div class="two" ng-transclude></div>';
            } else if (attrs.three !== undefined) {
                template = '<div class="three" ng-transclude></div>';
            } else {
                template = '<div class="one" ng-transclude></div>';
            }
            console.log(template);
        }
    };
})

HTML:

<col three>Three</col>
<col two>Two</col>
<col>Nothing</col>

控制台显示正确:

  

<div class="three" ng-transclude></div>
  <div class="two" ng-transclude></div>
  <div class="one" ng-transclude></div>

但输出显示默认/初始<div class="one" ng-transclude></div>

2 个答案:

答案 0 :(得分:2)

这是因为模板是在link函数被触发之前收集的,如果您只是尝试更改类,那么只需执行类似的操作。

.directive('col', function () {
    var template = '<div class="{{class}}" ng-transclude></div>';
    return {
        restrict: 'E',
        scope: {},
        transclude: true,
        replace: true,
        template: template,
        link: function (scope, ele, attrs) {
            $scope.class = attrs.three ? 'three' : attrs.two ?'two' : attrs.one ? 'one' : '';
        }
    };
});

除此之外,我不知道你将如何完成它。

答案 1 :(得分:0)

当您在链接函数中说'template ='xxx'时,它会引用您的模板变量,而不是返回对象上的属性。试试这个:

.directive('col', function () {
    var result = {
        restrict: 'E',
        scope: {},
        transclude: true,
        replace: true,
        template: template,
        link: function (scope, ele, attrs) {
            if (attrs.two !== undefined) {
                result.template = '<div class="two" ng-transclude></div>';
            } else if (attrs.three !== undefined) {
                result.template = '<div class="three" ng-transclude></div>';
            } else {
                result.template = '<div class="one" ng-transclude></div>';
            }
            console.log(result.template);
        }
    };
    return result;
})