I have small directive to add required
class to closest label of form element. It works fine with attribute required
, but when using ng-required
it seems to be not binding directive to element.
How to dynamically trigger directive binding on ng-required
change?
NOTE I don't want to add any extra markup to HTML if possible, to have one global directive
var app = angular.module('app',[]);
app.controller('myController',function ($scope) {
$scope.isRequired = false;
$scope.$watch('isRequired', function () {
angular.element('#html').text(angular.element('#required-element').html());
})
});
app.directive('required', function () {
return {
restrict: 'A',
link: function ($scope, $elem) {
console.log('Linking');
label = $elem.closest('.input-container').find('label');
if (label.length) {
label.addClass('required');
}
}
};
});
.required:before {
content: '*';
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app"ng-controller="myController">
<div class="input-container">
<label>Label</label>
<input type="text" required/>
</div>
<div id="required-element" class="input-container">
<label>Label Dynamic</label>
<input type="text" ng-required="isRequired == true"/>
</div>
<label><input type="checkbox" ng-model="isRequired"/> Make required: {{isRequired | json}}</label>
<hr/>
<span id="html"></span>
</div>