4

Is there a way I can use conditional AngularJS data binding?

I want to bind my model to vm.ABC if bool has true value, if it has false, I want to bind my model to vm.XYZ.

3
  • and when does this condition happen, like at the time bootstraping or later Commented Sep 6, 2017 at 11:08
  • Check the answer, this is what you need Commented Sep 6, 2017 at 11:08
  • @Rakeschand at the time of bootstrapping. Commented Sep 6, 2017 at 11:09

2 Answers 2

3

You can use ng-if for this. Here is the simple example,

//if bool is true then bind vm.ABC
<input type='text' ng-if='bool' ng-model='vm.ABC' />

//if bool is false then bind vm.XYZ
<input type='text' ng-if='!bool' ng-model='vm.XYZ' />

This will work great for your condition. And also by using ng-if the HTML is not render on the UI if the condition is false.

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

2 Comments

This is not what OP asked, he is asking for ng-model binding, read the question again
That was just an example. However i have changed it.
3
<div ng-init="vm.thirdVar = bool ? vm.ABC : vm.XYZ">
    <input type="text" ng-model="vm.thirdVar">
</div>

vm.thirdVar define this in controller

4 Comments

let me give it a try
are you using AngularJS or Angular2
I'm using AngularJs 1.6
Thanks for the help @Rakeschand

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.