alfredopacino alfredopacino - 2 months ago 10
AngularJS Question

disable submit button in directive

I simply want to add the class

disable
when
form.$valid
is
false
. The first submit button (not directive) obiouvsly works, but I don't know how to make visible the form state inside the directive. I cannot hardcode the form name in directive, it should be reusable in several forms..

<form id="tA" name="form" ng-controller="ctrl" ng-submit="form.$valid && save()" novalidate>

<input type="text" class="form-control" placeholder="title" name="name" ng-model="model.name" required ng-required="true">

<button class="btn btn-default" ng-class="{'disabled' : !form.$valid}" class="btn btn-default">Submit</button>

<button-raised disabled="!form.$valid">directive Submit</button-raised>





app.directive('buttonRaised', function() {
return {
restrict: 'E',
template: '<button class="mdl-button" ng-class="ngClass" ng-transclude></button>',
scope: {
ngModel: '='
},
transclude: true,
link: function($scope, el, $attrs,formCtrl) {
console.log(formCtrl)
$scope.ngClass = {
// 'disabled': $scope.$parent.formCtrl.$valid,
};
}
};
});

Answer

one way to do this is to pass your boolean as a parameter of your directive :

app.directive('buttonRaised', function() {
return {
    restrict: 'E',
    template: '<button class="mdl-button" ng-disabled="disabled" ng-class="ngClass" ng-transclude></button>',
    scope: {
        ngModel: '=',
        disabled: '='
    },
    transclude: true,
    link: function($scope, el, $attrs,formCtrl) {
        console.log(formCtrl)
        $scope.ngClass = {
           // 'disabled': $scope.$parent.formCtrl.$valid,
        };
    }
};

});