0

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.

Mithun Shreevatsa
  • 3,588
  • 9
  • 50
  • 95

3 Answers3

0

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 />
Sudharsan Selvaraj
  • 4,792
  • 3
  • 14
  • 22
  • Yup, this can be done. But constraint is this textfields are forming in a loop, so with this approach, we will have 2 input fields always. And if 10, it is double. – Mithun Shreevatsa Feb 14 '17 at 13:43
0

You could use bracket notation to set your ng-model as a property of an object (vm.modelCollection) and return the name of the given property with the isUniqueAttribute method.

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

and then

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

I don't know if this approach suits your needs

Osman Cea
  • 1,467
  • 9
  • 18
0

I would suggest utilizing a Static Model with Dynamic Content. I have used "ng-init" in my sample to supply the dynamic data, although you can rely on controller to provide it as per your need. (as state here https://docs.angularjs.org/api/ng/directive/ngInit)

Sample Code:

$scope.Model = [];
$scope.SetModelWithDynamicContent = function(index) {
if ($scope.Model.indexOf(index) == -1) {
  //Add your conidition here(.isunique). I have used odd or even number.
  if (index % 2 == 0)
    $scope.Model.push({
      Property: "Bind vm.abc"
    });
  else
    $scope.Model.push({
      Property: "Bind vm.def"
    });
}

The complete code for it can be found at http://plnkr.co/edit/gFa26r?p=preview

Please remember to mark this as answer if it solves your problem!

DevCod
  • 280
  • 2
  • 11