【问题标题】:How to use a directive to dynamically change a template?如何使用指令动态更改模板?
【发布时间】:2014-04-27 21:07:25
【问题描述】:

我有这个指令

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

有什么想法吗?

【问题讨论】:

    标签: javascript angularjs templates angularjs-directive


    【解决方案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);
            }
        }
    }]);
    

    【讨论】:

    • 顺便说一句,如果我返回 HTML,它会作为一个刺痛进入 DOM。你知道如何返回纯 HTML
    • 查看 angular $compile 服务并检查更新。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2015-02-22
    • 2013-01-29
    • 1970-01-01
    • 2013-11-25
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多