且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-18 21:53:28

你可以将 htm 放入指令的 scope 并在模板中使用它.

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 字符串编译为模板,您需要使用 $compile 服务,只是可能的例子:

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