简体   繁体   English

Angular.js绑定模型到指令

[英]Angular.js binding model to directive

I'm trying to put together an Angular directive that will be a replacement for adding 我正在尝试将Angular指令放在一起,以代替添加

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. 在表单按钮元素上, canSave是在控制器中定义的函数,类似于以下内容,其中参数是表单的名称。

$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? 无论如何,从该指令中绑定ng-disabled指令还是该方法错误?

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 柱塞: 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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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