如何设置ng-disabled内部指令

时间:2014-02-15 22:10:29

标签: javascript angularjs

我的指令有

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应用于元素?

3 个答案:

答案 0 :(得分:13)

您可以将ng-disabled设置为范围变量,例如:

<input ng-disabled="isDisabled" />

然后在你的指令中你可以设置那个变量:

$scope.isDisabled = true;

答案 1 :(得分:13)

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

为什么要调用ng-disable?您已经自己一次评估了这个条件,因此再次使用ng-disable进行评估是多余的。

答案 2 :(得分:4)

//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';
            });

归功于Ilan Frumer

相关问题