Creating angularjs directive with id attribute for internal html but id still on outer html
angularjs, angularjs-directive, javascript
Solution
From the Angular directive guide:
The replacement process migrates all of the attributes / classes from the old element to the new one.
So, what you're seeing is expected behavior.
Rather than remove the attribute in link I'd just create a new attribute, for instance `check-id` and use it like this:
<fancy-checkbox colour="red" check-id="mycheckbox"></fancy-checkbox>
add it to your scope:
checkId : '@',
and use that within your template:
template : '<div class="fancyCheckbox">' +
'<input type="checkbox" id="{{ checkId }}" />' +
'<label for="{{ checkId }}" ></label>' +
'</div>',
demo fiddle
Problem
So I have created this checkbox directive that is made up of a label and input element. I want to set an id attribute on the directive and set this as the "id" of the input element and the label "for" attribute. This works fine, but the problem is that it remains on the outer html which is a div, so it breaks my directive. I thought that if you had the directive set to replace : true, then this would remove the html that defined the directive . The directive is as follows ``` angular.module('journal.directives', []). directive('fancyCheckbox', function(){ return { restrict : 'EA', replace : true, template : '<div class="fancyCheckbox">' + '<input type="checkbox" id="{{ id }}" />' + '<label for="{{ id }}" ></label>' + '</div>', scope : { colour : '@', id : '@', }, link : function(scope, elem, attrs){ var spotColourClass; var valid_colours = ['blue', 'green', 'gray', 'purple', 'blue', 'orange', 'charcoal', 'light', 'yellow', 'red']; if(valid_colours.indexOf(scope.colour) !== -1){ spotColourClass = scope.colour + "spot"; }else{ spotColourClass = 'greenspot'; } elem.addClass(spotColourClass); } }; }); ``` When I call my directive as ``` <fancy-checkbox colour="red" id="mycheckbox"></fancy-checkbox> ``` and it becomes ``` <div class="fancyCheckbox ng-isolate-scope greenspot" colour="green" id="mycheckbox"> <input type="checkbox" id="mycheckbox"> <label for="mycheckbox"></label> </div> ``` You see that the "id" is still on the outer div, which is not what I want. I assumed that this would be removed. So do I just have to remove it manually in the linking function Hope someone can help Thanks