Подтвердить что ты не робот

Как установить внутреннюю директиву ng-disabled

Моя директива имеет

link: function ($scope, $elm, $attrs) {
    var status = $scope.item.status
    if (status) {
        var statusName = status.name,
            item = $scope.item;
        if (statusName === 'USED') {
            $attrs.$set('ng-disabled', true); // this doesn't work
        } else {
            $elm.attr('ng-disabled', false);
        }
    }
}

Итак, мой вопрос:

Как применить ng-disabled к элементу с этой директивой?

4b9b3361

Ответ 1

Вы должны установить ng-disabled в переменную области видимости, например:

<input ng-disabled="isDisabled" />

И затем внутри вашей директивы вы можете установить эту переменную:

$scope.isDisabled = true;

Ответ 2

if (statusName === 'USED') {
    $attrs.$set('disabled', 'disabled');
} else {
    $elm.removeAttr('disabled');
}

Зачем вообще вызывать ng-disable? Вы уже сами оцениваете это условие, поэтому повторное вычисление ng-disable излишне.

Ответ 3

//html
<div ng-app="miniapp" ng-controller="MainCtrl">
    <input type="submit" mydir>
</div>
//js
'use strict';
            var app = angular.module('miniapp', []);
            app.directive('mydir', function ($compile) {
                return {
                    priority:1001, // compiles first
                    terminal:true, // prevent lower priority directives to compile after it
                    compile: function(el) {
                        el.removeAttr('mydir'); // necessary to avoid infinite compile loop
                        return function(scope){
                            var status = scope.item.status
                            if (status === 'USED') {
                                el.attr('ng-disabled',true);
                            } else {
                                el.attr('ng-disabled',false);
                            }
                            var fn = $compile(el);
                            fn(scope);
                        };
                    }


                };
            });
            app.controller('MainCtrl', function ($scope) {
                $scope.item = {};
                $scope.item.status = 'USED';
            });

кредит Илан Фрумер