Label for not working in angularjs directive
angularjs, angularjs-directive, html, javascript
Solution
Are you sure the ID you are using is unique?
Another option is to nest the `<input>` tag in the `<label>`, in that case you don't need the `for` argument:
var elemTpl = '<div> ' +
'<div class="form-group col-md-{{cols}}" >' +
'<label class="control-label input-sm">{{text}}' +
'<input type="{{type}}" ng-model="value" name="' + attrs.id + '" id="' + attrs.id + '" class="form-control input-sm szpFocusable" placeholder="{{placeholder}}" ng-required="required" spellcheck="false"/>' +
'</label>' +
'</div> ' +
'</div>';
Note: The real answer is in the 2nd comment below: In a directive the content of element template is placed within the directive tag, in this case resulting in the id being used twice. This can be solved by adding `replace : true` to the return value of the directive. This will replace your directive tag with the contents of your template.
app.directive('myDirective', function() {
return {
replace: 'true',
template: templateThatUsesId
};
});
Problem
I am using this custom template inside a directive to generate customized input fields with associated labels: ``` template: function(elem, attrs) { var elemTpl = '<div> ' + '<div class="form-group col-md-{{cols}}" >' + '<label for="{{id}}" class="control-label input-sm">{{text}}</label> ' + '<input type="{{type}}" ng-model="value" name="' + attrs.id + '" id="' + attrs.id + '" class="form-control input-sm szpFocusable" placeholder="{{placeholder}}" ng-required="required" spellcheck="false"/>' + '</div> ' + '</div>'; return elemTpl; } ``` The problem is that when the label is clicked, the input field is not being focused. When moving the code outside the directive and putting the input tags directly in the html, all works fine. The id and the name attributes are bound correctly to the appropriate scope fields.