0

I'm trying to put together an Angular directive that will be a replacement for adding

ng-disabled="!canSave(schoolSetup)"

On a form button element where canSave is a function being defined in a controller something like the following where the parameter is the name of the form.

$scope.canSave = function(form) {
    return form.$dirty && form.$valid;
};

Ideally I'd love the directive on the submit button to look like this.

can-save="schoolSetup"

Where the string is the name of the form.

So... how would you do this? This is as far as I could get...

angular.module('MyApp')
    .directive('canSave', function () {
        return function (scope, element, attrs) {

            var form = scope.$eval(attrs.canSave);

            function canSave()
            {
                return form.$dirty && form.$valid;;
            }

            attrs.$set('disabled', !canSave());
        }

    });

But this obviously doesn't bind properly to the form model and only works on initialisation. Is there anyway to bind the ng-disabled directive from within this directive or is that the wrong approach too?

2 Answers 2

3
angular.module('MyApp')
    .directive('canSave', function () {
        return function (scope, element, attrs) {
            var form = scope.$eval(attrs.canSave);

            scope.$watch(function() {
                return form.$dirty && form.$valid;
            }, function(value) {
                value = !!value;
                attrs.$set('disabled', !value);
            });
        }
    });

Plunker: http://plnkr.co/edit/0SyK8M

Sign up to request clarification or add additional context in comments.

Comments

2

You can pass the function call to the directive like this

function Ctrl($scope) {
    $scope.canSave = function () {
        return form.$dirty && form.$valid;
    };
}

app.directive('canSave', function () {
    return {
        scope: {
            canSave: '&'
        },
        link: function (scope, element, attrs) {
            attrs.$set('disabled', !scope.canSave());
        }
    }
});

This is the template

<div ng-app="myApp" ng-controller="Ctrl">
    <div can-save="canSave()">test</div>
</div>

You can see the function is called from the directive. Demo

1 Comment

Thanks for your answer! Would work like this but was trying to remove the controller from being needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.