user5752078
user5752078

Reputation:

How to set attributes, if ng-if condition is true

How can I set attribute if ng-if returns true in below code data-validator="" and data-validator-msg="" set only when condition is true and if it returns false then both attribute not to be set but at all conditions radio button should appear.

In current code, condition is working but radio button visible only at true condition.

<input ng-model="user.duration" value="{{ x.title}}" type="radio" ng-if="$index==5" data-validator="required" data-validator-msg="Select one radio button">{{ x.title}}

radio buttons

What exactly mistake I am doing?

Upvotes: 1

Views: 2810

Answers (4)

lex82
lex82

Reputation: 11297

The problem is that ng-if only renders the respective element when the condition is true. What you want is to pass different values as attributes depending on a condition. You can do this for example with the conditional operator:

<input ng-model="user.duration"
       value="{{ x.title}}"
       type="radio"
       data-validator="{{ $index==5 ? 'required' : '' }"
       data-validator-msg="{{ $index==5 ? 'required' : 'Select one radio button' }">
  {{x.title}}
</input>

Upvotes: 0

Mitja Kramberger
Mitja Kramberger

Reputation: 270

You can do it with a simple condition logic:

<input
  ng-model="user.duration" 
  value="{{ x.title}}" 
  type="radio" 
  data-validator="{ ($index===5 && 'required') || '' }" 
  data-validator-msg="{ ($index===5 && 'Select one radio button') || '' }" 
>{{ x.title}}

Upvotes: 0

Alex Pollan
Alex Pollan

Reputation: 873

Simplest solution:

<input ng-model="user.duration" value="{{x.title}}" type="radio" ng-if="$index==5" data-validator="required" data-validator-msg="Select one radio button">{{x.title}}

<input ng-model="user.duration" value="{{x.title}}" type="radio" ng-if="$index!=5">{{x.title}}

(ng-if removes the element from the DOM if the condition evaluates to false)

Upvotes: 1

Avijit Gupta
Avijit Gupta

Reputation: 5756

I wrote a directive for you:

.directive("isValidatorDirective", function() {
  return {
    restrict: "A",
    scope: {
      applyValidator: '=',
      msg: '@',
      validator: '@'
    }
    link: function(scope, elem, attrs) {
      if (scope.applyValidator) {
        elem.attr('data-validator-msg', scope.msg); 
        elem.attr('data-validator', scope.validator);
      }
      else {
        elem.removeAttr('data-validator-msg');
        elem.removeAttr('data-validator');
      }
    }
  };
});

Use it as follows:

<input is-validator-directive apply-validator="$index === 5" validator="required" msg="Select one radio button" ng-model="user.duration" value="{{ x.title}}" type="radio">{{x.title}}

Hope it helps you!

Upvotes: 1

Related Questions