0

考虑到下面的代码,我试图用2个不同的对象动态地构造ng-model,如果它满足uniqueAttribute条件的话。有没有办法分配一个函数并动态创建ng-model?

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

下面是它返回vm.abcvm.def绑定到ng-model

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

的功能,但它引发的错误为:

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

有没有一种方法来处理它喜欢或任何替代方法来实现这一目标?

我可以通过分配一个单独的对象,然后将其分类为2个不同的对象作为最终选项。但是,只是想知道是否可以毫不费力地处理它。

+0

您的代码必须正常工作。是否定义了'entityDefinition'(这是参数)?该问题仅在参数内。 – SaiUnique

+0

无法将功能分配给ng-model – Mithun

+0

需要使用参数本身来构建它。如果它是真的,它会阻止绑定到trueobject或falseobject – Mithun

回答

0

在两个模型中使用两个不同的元素,并在ng-if的帮助下根据标志切换所需的元素。

<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 /> 
+0

传递的数据是可以做到的。但是约束是这个文本字段正在形成一个循环,所以使用这种方法,我们总会有2个输入字段。如果是10,则是双倍。 – Mithun

0

你可以使用括号符号来设置ng-model为的objectvm.modelCollection)的属性,并与isUniqueAttribute方法返回给定属性的名称。

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

然后

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

如果这种方法适合您的需要

0

我会建议利用与动态内容的静态模型,我不知道。我在示例中使用了“ng-init”来提供动态数据,但是您可以依赖控制器根据您的需要提供它。 (如状态这里https://docs.angularjs.org/api/ng/directive/ngInit

示例代码:

$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" 
    }); 
} 

它的完整代码可以在http://plnkr.co/edit/gFa26r?p=preview

发现请记住,以纪念本作的答案,如果它解决您的问题!

相关问题