我有一个小指令将required
类添加到表单元素的最近标签。它适用于 attribute required
,但使用ng-required
时似乎没有将指令绑定到元素。
如何在ng-required
更改时动态触发指令绑定?
注意如果可能的话,我不想向 HTML 添加任何额外的标记,以拥有一个全局指令
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>