Avoid using extra DOM nodes when using nginclude

后端 未结 5 714
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 10:23

I\'m struggling to wrap my mind around how to have an ng-include not use an extra DOM element as I\'m building an angular app from a plain-HTML demo. I\'m working with pretty sl

5条回答
  •  被撕碎了的回忆
    2021-01-31 10:44

    Edit: After some research and for the sake of completeness, I've added some info. Since 1.1.4, the following works:

    app.directive('include',
        function () {
            return {
                replace: true,
                restrict: 'A',
                templateUrl: function (element, attr) {
                    return attr.pfInclude;
                }
            };
        }
    );
    

    Usage:

    There is, however, one gotcha: the template cannot be dynamic (as in, passing a variable through scope because $scope, or any DI for that matter, is not accessible in templateUrl - see this issue), only a string can be passed (just like the html snippet above). To bypass that particular issue, this piece of code should do the trick (kudos to this plunker):

    app.directive("include", function ($http, $templateCache, $compile) {
        return {
            restrict: 'A',
            link: function (scope, element, attributes) {
                var templateUrl = scope.$eval(attributes.include);
                $http.get(templateUrl, {cache: $templateCache}).success(
                    function (tplContent) {
                        element.replaceWith($compile(tplContent.data)(scope));
                    }
                );
            }
        };
    });
    

    Usage:

提交回复
热议问题