Adding form validation to custom directive in angular

128 Views Asked by At

I am aware that the question has been asked before but i do not know how to implement the asnwers into my problem. I have a tri-state boolean directive in angular and I am not sure how to add validation states to the directive so that the form can see i the value is valid (not null)

app.directive('customBoolean', function(){
    return {
    restrict: 'E',
    replace: true,
    scope: {
        boolValue: '=',
        required: '@'
    },
    template: '<button class="btn btn-default btn-xs" ng-click="toggle()" style="width: 70px">{{ boolValue | bool_to_string }}</button>',
    controller: function ($scope, $element){

    $scope.toggle = function(){
        if ($scope.boolValue == null)
        { $scope.boolValue = true; }
        else if ($scope.boolValue == true)
        { $scope.boolValue = false; }
        else { $scope.boolValue = $scope.required ? true  : undefined; }
    };
  }
 }
});

below is a plnkr link of what i have so far. Anyone have any ideas?

plnkr link

1

There are 1 best solutions below

0
On

Use ngModel instead of boolValue. require the ngModel in your directive, and then set the validity using $setValidity.

app.directive('customBoolean', function(){
return {
restrict: 'E',
require : 'ngModel'
replace: true,
scope: {
    boolValue: '=',
    required: '@'
},
template: '<button class="btn btn-default btn-xs" ng-click="toggle()" style="width: 70px">{{ boolValue | bool_to_string }}</button>',
link: function ($scope, $element,$attrs,ngModel){
if (//your invalid conditions){
  ngModel.$setValidity(attrs.ngModel,true/false);
}
$scope.toggle = function(){
    if ($scope.boolValue == null)
    { $scope.boolValue = true; }
    else if ($scope.boolValue == true)
    { $scope.boolValue = false; }
    else { $scope.boolValue = $scope.required ? true  : undefined; }
};
}}});