Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I include HTML into a page with AngularJS from an HTML file?

I have some code that I have taken over. It looks like this:

<div id="init"
     data-admin-template
     ng-show="ss.display.init"
     data-template-url="init.html">
</div>

There's a directive adminTemplate:

app.directive('adminTemplate', ['stateService', function (stateService) {
    return {
        restrict: 'A',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}]); 

I am not very familiar with templates and it seems that this directive does not really do much. Is there a way I can do this without the directive?

Upvotes: 0

Views: 103

Answers (1)

james
james

Reputation: 4573

As @Oli said in the comments, ng-include is definitely one solution. There are others as well - angular likes to offer you just enough options to leave you doubting yourself - but i'm wondering what you'd actually gain by changing it.

With ng-include you'd need to add a controller to to your html, to supply stateService (if you don't do it here, you'd have to add it to every different admin template). So you'd end up with:

<div id="init"
     ng-include="/Content/app/admin/templates/init.html"
     ng-show="ss.display.init"
     ng-controller="AdminController">
</div>

So you end up with the same amount of attributes, you need the whole template path and it becomes less readable. Looking at what you have now, it's clear to see the intent.

You could also go one step further and give it the flexibility of being an element or attribute

<admin-template
    id="init"
    ng-show="ss.display.init"
    data-template-url="init.html">
</admin-template>


app.directive('adminTemplate', ['stateService', function (stateService) {
    return {
        restrict: 'EA',
        templateUrl: function (elem, attrs) {
            return "/Content/app/admin/templates/" + attrs.templateUrl;
        },
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
        }
    };
}]);

It may appear to be doing very little, but my feeling is that the previous developer has refactored out repetition, to get to this little directive. I'd argue that as it is it removes boiler plate, allows easy re-usability and communicates intent well in your mark up.

Upvotes: 1

Related Questions