在AngularJS中动态设置ng-model value为js变量的值

Setting ng-model value dynamically to the value of js variable in AngularJS

本文关键字:js 变量 value ng-model AngularJS 动态 设置      更新时间:2023-09-26

以前也有人问过类似的问题,我也尝试过给他们的解决方案,但我的问题有点不同。

假设我的控制器中有一个这样的对象数组

$scope.objArray = [
  {
    id:1,
    name:"placeholder1"
  },
  {
    id:2,
    name:"placeholder2"
  }
];

现在基于这个数组,我将动态生成如下的表单

  <div ng-repeat="field in fields">
    {{field.field_name}} </br>
    <input type="text" ng-model="field.field_name"><br>
  </div>

在此形式中,我希望ng-model值设置为placeholder1placeholder2,而不是像field.field_name那样的javascript变量,因为我的目标来自另一个包含如下html的源。

<p>this is sample html {{placeholder1}}. again sample html {{placeholder2}} </p>

我没有这些JS变量在这里。到目前为止,我还没有找到适合我的解决办法。

链接到plunk:http://plnkr.co/edit/ttaq0l3PDRu4piwSluUX?p=preview

在你的例子中,它看起来像这样:

<div ng-repeat="field in fields">
    {{field.field_name}}
    <br>
    <input type="text" ng-model="$parent[field.field_name]">
    <br>
</div>

注意,您必须使用$parent引用,因为在您的情况下,您希望设置外部作用域的属性(其中定义了objArray),然而ngRepeat每次迭代创建子作用域,因此您需要更进一步。

演示:

http://plnkr.co/edit/35hEihmxTdUs6IofHJHn?p=info