如何使用指令动态更改模板?

时间:2014-04-27 21:07:26

标签: javascript angularjs templates angularjs-directive

我有这个指令

angular.module('starter.directive', [])
    .directive('answer', ['Helper', function (Helper) {
        return {
            require: "logic",
            link: function (scope, element, attrs, logicCtrl) {
                var htm = '';
                if(logicCtrl.test == 'a') {
                    htm = '<p>a</p>'
                }
                if(logicCtrl.test == 'b') {
                    htm = '<p>b</p>'
                }
            },
            template: '' // somehow use htm here
        }
    }]);

我尝试将htm用于template

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以将htm放入scope指令并在模板中使用它。

angular.module('starter.directive', [])
.directive('answer', ['Helper', function (Helper) {
    return {
        require: "logic",
        link: function (scope, element, attrs, logicCtrl) {
            scope.htm = '';
            if(logicCtrl.test == 'a') {
                scope.htm = '<p>a</p>'
            }
            if(logicCtrl.test == 'b') {
                scope.htm = '<p>b</p>'
            }
        },
        template: '{{htm}}' // somehow use htm here
    }
}]);

更新

要将html字符串编译为模板,您需要使用$compile服务,只是可能的示例:

angular.module('starter.directive', [])
.directive('answer', ['Helper', function (Helper) {
    return {
        require: "logic",
        link: function (scope, element, attrs, logicCtrl) {
            var htm = '';
            if(logicCtrl.test == 'a') {
                htm = '<p>a</p>'
            }
            if(logicCtrl.test == 'b') {
                htm = '<p>b</p>'
            }
            var el = angular.element(htm);
            compile(el.contents())(scope);
            element.replaceWith(el);
        }
    }
}]);