How to use a directive to dynamically change a tem

2019-09-11 16:03发布

问题:

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

I'm trying to use the htm for the template,

Any ideas?

回答1:

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

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