TidharPeer
TidharPeer

Reputation: 3797

In Angular JS - how to use ng-include to make my code generic and reusable?

Using the AngularJS, I want to use ng-include to make my code generic.

So here is my problem:

I want to have my 'ang-attribute.html' file used in the ng-include to be as generic as possible, and for that I want to get the attribute name outside of the html.

With something like this:

<div data-field-name="display_name">
    <div ng-include="'ang-attribute.html'"></div>
</div>

In my html file I would like to use the data-field-name, and then use it again with a different value.

I tried to get it via DOM... and couldn't find a way to do that.

So in my ng-include html file I have the following line:

<div ng-controller="attributeCtrl">
    <div class="my-profile-constant-text">{{displayAttribute}}:</div>
....
</div>

Maybe there is a way to pass a constructor to the controller and then I could pass my data-field-name into it? Or any other solution?

Thanks!

Upvotes: 0

Views: 1076

Answers (1)

Dan Saltmer
Dan Saltmer

Reputation: 2165

I believe you want to be looking at directives, this has an attributes object easily accessible after the dom has rendered to re-use. Html

<my-directive field-name="display_name"></my-directive>

Directive

angular
.module("myApp", [])
.directive("myDirective", function() {
    return {
        restrict: "E",
        template: "<div>{{exposeAttribute}}</div>",
        //templateUrl: "mytemplate.html",
        link: function(scope, element, attr) {
            scope.exposeAttribute = attr.fieldName;
        }
    };
});

http://jsfiddle.net/mhCaD/

Upvotes: 3

Related Questions