JSFiddle - React, Tailwind, and code Playground
HTML
<form name="myform" ng-app="plunker" ng-controller="MainCtrl">
<input type="text" ui-constraints="myconstraints" data-ng-model="mydata" name="myfield" />
<span style="color: red;" ng-show="myconstraints != undefined">*</span>
{{mydata}}</br>
<button data-ng-click="toggleConstraints()">Toggle Required</button></br>
<tt>myform.$valid = {{myform.$valid}}</tt></br>
<tt>myform.myfield.$valid = {{myform.myfield.$valid}}</tt>
</form>
JavaScript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $timeout) {
$scope.mydata = "test string";
$scope.myconstraints = [{key: "required", value: "true"}];
$scope.toggleConstraints = function(){
if($scope.myconstraints !== undefined){
$scope.myconstraints = undefined;
}
else{
$scope.myconstraints = [{key: "required", value: "true"}];
}
};
}).directive('uiConstraints', [function(){
function applyConstraints(element, newVal, oldVal){
//remove old constraints
if(oldVal !== undefined && oldVal !== null){
for (var i = 0; i < oldVal.length; i++) {
element.removeAttr(oldVal[i].key);
}
}
//apply new constraints
if(newVal !== undefined && newVal !== null){
for (var i = 0; i < newVal.length; i++) {
var constraint = newVal[i];
element.attr(constraint.key, constraint.value);
}
}
}
function link(scope, element, attrs){
scope.$watch(attrs.uiConstraints, function(newVal, oldVal){
applyConstraints(element, newVal, oldVal);
});
}
return {
restrict : 'A',
link : link
};
}]);