angular dynamic templating directives

前端 未结 1 1967
無奈伤痛
無奈伤痛 2020-12-20 08:39

I have a list of different field types and I want to apply a template based on type. I can get it to work if I use inline templates like this:

flowPageModule         


        
相关标签:
1条回答
  • 2020-12-20 08:55

    I got paid to create this, but since actually no one really care about the implementation (good or bad?)...I am feeling free to share this to the community. I adapted the loadT() function from another SO answer. You can find it searching for "dynamic template angular". The adapation here allows you to display an empty component while $http promise has not returned.

    usages

    <p dynamic template="'template/file.html'"></p>
    
    <p dynamic template="someObjectInController.value"></p>
    

    *transclusion doesn't work. So feel free to add/correct. The issue lies in the lack of documentation for the transclude function.

    cpanel.directive("dynamic",  ["$compile", '$templateCache', '$http',
        function ($compile, $templateCache, $http) {
            return {
                priority: 0,
                restrict: 'EA',
                replace: true,
                transclude: true,
                controller: 'SomeController',
                scope: {
                    template: "@template"
                },
                link: function (scope, iElement, iAttrs) {
    
                    scope.$parent.$watch(iAttrs.template, function (newvalue, oldvalue) {
                        if ((oldvalue !== newvalue) && (newvalue !== undefined) && (newvalue !== null)) {
                            loadT(newvalue);
                        } else if ((newvalue !== undefined) && (newvalue !== null)) {
                            loadT(newvalue);
                        } else {
                            //TODO
                        }
                    }, true);
    
                    function loadT(it) {
                        $http.get(it, { cache: $templateCache}).success(function (templateContent) {
                            iElement.replaceWith($compile(templateContent)(scope));
                        });
                    }
                }
            };
        }
    ]);
    
    0 讨论(0)
提交回复
热议问题