Search code examples
javascriptangularjsangular-ngmodeljavascript-databinding

Is there a way to assign a function and create ng-model dynamically?


Considering the below code, i am trying to construct ng-model dynamically with 2 different objects if it meets the uniqueAttribute condition.

<input type="text" class="form-control" ng-model="vm.isUniqueAttribute(entityDefinition)" required />

Below is the function where it returns vm.abc or vm.def to bind to ng-model

            vm.isUniqueAttribute = function(entityDef) {
                return entityDef.isUnique === 'true' ? 'vm.abc': 'vm.def';
            }

But it throws error as:

Error: [ngModel:nonassign] Expression 'vm.isUniqueAttribute(entityDefinition)' is non-assignable.

Is there a way to handle it like or any alternate way to achieve this?

I can do by assigning it some single object and later classify into 2 different object as a final option. But, just wondering if it can be handled without much effort.


Solution

  • use two different elements with two models and with the help of ng-if toggle the required element based on the flag.

    <input type="text" class="form-control" ng-model="vm.abc" ng-if="vm.isUniqueAttribute(entityDefinition)" required />
    <input type="text" class="form-control" ng-model="vm.def" ng-if="!vm.isUniqueAttribute(entityDefinition)"required />