将 ngModel 绑定到表达式的值

Binding ngModel to expression's value

我有一个场景,其中 属性 ng-model 应该绑定到来自数据库的值,作为业务逻辑的一部分。

为简单起见,我创建了这个 example

function TodoCtrl($scope) {
    $scope.field1 = "PropertyFromDB";
    $scope.PropertyFromDB = "hello world";
}

<div ng-app>
  <h2>ngModel BINDING EXAMPLE</h2><br/>
  <div ng-controller="TodoCtrl">
      <div ng-init="imod = field1">
          <input type="text" ng-model="imod"></input>
      </div>
  </div>
</div>

在此示例中,field1 是来自 DB(即 PropertyFromDB)的值 属性,并且 ng-model 应该绑定到 PropertyFromDB 而不是 field1。 所以,就像我想在 ng-model 的表达式语法中评估表达式,但我无法这样做。

谢谢

您根本无法使用任何表达式设置 ng-model 的值。另一种方法是更改​​从服务器返回的 JSON 的结构。

标记

<div ng-controller="TodoCtrl">
    <div ng-repeat="field in properties">
        <label>{{field.property}}</label>
        <input type="text" ng-model="field.value" />
    </div>{{properties}}
</div>

代码

function TodoCtrl($scope) {

    $scope.properties = [{
        property: 'PropertyFromDB',
        value: "hello world"
    }, {
        property: 'PropertyFromDB1',
        value: "hello world1"
    }]
}

Fiddle Here

可以 使用 this 引用当前范围并读取其 属性,例如:

<div ng-init="imod = field1">
  <input type="text" ng-model="this[imod]"></input>
</div>

但这是一种非常不寻常且不方便的创建视图模型的方法。

我建议创建一个更好的 structure/object,其中包含 field/value 组合并在范围内设置该对象,而不是在范围内单独设置字段和值。