How to set ng-disabled inside directive

后端 未结 3 1488
栀梦
栀梦 2020-12-18 22:46

My directive has

link: function ($scope, $elm, $attrs) {
    var status = $scope.item.status
    if (status) {
        var statusName = status.name,
                 


        
相关标签:
3条回答
  • 2020-12-18 23:05

    You would set ng-disabled to a scope variable, ex:

    <input ng-disabled="isDisabled" />
    

    And then inside your directive you can set that variable:

    $scope.isDisabled = true;
    
    0 讨论(0)
  • 2020-12-18 23:23
    if (statusName === 'USED') {
        $attrs.$set('disabled', 'disabled');
    } else {
        $elm.removeAttr('disabled');
    }
    

    Why invoke ng-disable at all? You're already once evaluating the condition yourself, so having ng-disable evaluating it again is redundant.

    0 讨论(0)
  • 2020-12-18 23:23
    //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';
                });
    

    credit to Ilan Frumer

    0 讨论(0)
提交回复
热议问题