【问题标题】:Is there a way to assign a function and create ng-model dynamically?有没有办法分配一个函数并动态创建 ng-model?
【发布时间】:2017-02-14 13:32:17
【问题描述】:

考虑到下面的代码,如果ng-model满足uniqueAttribute条件,我会尝试用2个不同的对象动态构造它。

<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';
            }

但它会抛出错误:

错误:[ngModel:nonassign] 表达式 'vm.isUniqueAttribute(entityDefinition)' 是不可赋值的。

有没有办法像处理它一样或任何替代方法来实现这一点?

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

【问题讨论】:

  • 您的代码必须能正常工作。 entityDefinition(这是参数)是否已定义?问题仅在参数范围内。
  • 无法将功能分配给 ng-model
  • 需要使用参数本身来构建它。如果它是真的,它会绑定到 trueobject 或 falseobject
  • 该函数调用是否可用的参数值?
  • 是的。从 ng-repeat 循环传递的数据

标签: javascript angularjs angular-ngmodel javascript-databinding


【解决方案1】:

在两个模型中使用两个不同的元素,并在 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 />

【讨论】:

  • 是的,这可以做到。但约束是这个文本字段是在一个循环中形成的,所以使用这种方法,我们将始终有 2 个输入字段。如果是 10,则为双倍。
【解决方案2】:

您可以使用括号表示法将您的ng-model 设置为object (vm.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';
 }

我不知道这种方法是否适合您的需求

【讨论】:

    【解决方案3】:

    我建议使用具有动态内容的静态模型。我在我的示例中使用了“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找到

    如果它解决了你的问题,请记得标记为答案!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多