本文介绍了如何使用指令来动态地改变模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的指令

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 模板

任何想法?

推荐答案

您只需把 HTM 范围指令,并用它的内部模板

You can just put htm into scope of directive and use it inside template.

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串到你需要使用的服务,只是可能的例如:

UPDATE

To compile html strings into template you need to use $compile service, just possible example:

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);
        }
    }
}]);

这篇关于如何使用指令来动态地改变模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:47
查看更多