Fidel90
Fidel90

Reputation: 1838

Apply attributes to custom nested element in an angular directive

I am currently building one of my first custom HTML Element with an AngularJS directive. I want to customize the range input type from HTML5. So far so good, my first steps was made of success. But now I want to enhance the current state with a nested template. At the moment I have sth. like this:

.directive("mySlider", [function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            min: "@",
            max: "@",
            step: "@?",
            ngModel: "="
        },
        template: "<input class='my-slider' type='range'>",
        link: function ($scope, $element) {

            //some logic here
        }
    }
}]);

With that, if I use

<my-slider min="0" max="10" step="1" ng-model="sth"></my-slider>

I get a replacement like so:

<input class="my-slider" type="range" min="0" max="10" step="1" ng-model="sth">

Thats nice as the attributes from scope are written to the input type and can then be used directly.

But here is my problem: Now I want some output HTML like:

<div>

<label>blah</label>

<input class="my-slider" type="range" min="0" max="10" step="1" ng-model="sth">

</div>

So my input element should be nested into a div, maybe with additional element like a label or sth. But when I update my template and just go around nesting my input there, all the attributes from the directive scope are applied to the root element (the div in this case). I don't want them there but on the input element.

Is it possible and how can I achieve to apply certain attributes from the directives scope to different specific elements?

Upvotes: 0

Views: 569

Answers (1)

Jonathan Rowny
Jonathan Rowny

Reputation: 7588

Change ngModel: "=" to sth: "=ngModel" to get the input model working. Use {{}} notation as you pointed out in the comments here for the attributes. And then make your parent attributes something like data-min so you don't have ugly source code.

Upvotes: 1

Related Questions