简体   繁体   中英

Angular.js binding model to directive

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM