2

I am attempting to add a HTML attribute to a form field to disable it if a property is true in a JSON file.

On my form field I have added data-is-disabled={{field.rules.disabled}} which is read in from the following from the JSON

"rules" : {
    "disabled": "true"
}

I then have a directive in my module where I am wanting to remove that attribute and replace it with a disabled attribute to disable the field.

app.directive ('isDisabled', function($compile) {
    return {
        restrict: 'A',
        compile: function (element) {
            element.removeAttr("data-is-disabled");
            element.attr("disabled");
            var fn = $compile(element);
            return function(scope){
                fn(scope);
            };
        }
    }
});

It seems overly complicated, however it is necessary for multiple different field type situations, in this case the field needs to be disabled.

I have tried a few different solutions from around SO, but I haven't got it working yet. The attribute remains as data-is-disabled="true".

Many thanks in advance.

2 Answers 2

3

Make it simpler and use this.

https://docs.angularjs.org/api/ng/directive/ngDisabled

ng-disabled={{field.rules.disabled}}

Be careful and check your data because true is a string, instead do...

ng-disabled={{JSON.parse(field.rules.disabled)}}

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I can't believe it was actually as simple as that! Thank you for such a quick and accurate answer!
No problem, I ran into the same problem several months ago.
1

use this link property:

directive ('isDisabled', function() {
    return {
        restrict: 'A',
        scope : {
          isDisabled : "="
        },
        link : function(scope, ele, attr){
          if(scope.isDisabled){
            ele.attr("disabled", true);
          }
        }
}

see link : https://plnkr.co/edit/01JnAyDEce2p43aHlL83?p=preview

1 Comment

Thank you very much @sandeep

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.