【问题标题】:Setting ng-model value dynamically to the value of js variable in AngularJS将 ng-model 值动态设置为 AngularJS 中 js 变量的值
【发布时间】:2015-07-08 18:32:50
【问题描述】:

以前有人问过类似的问题,我已经尝试过为他们提供的解决方案,但我的问题略有不同。

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

$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,而不是像javascript 变量,如field.field_name,因为我的目标来自另一个包含html 的来源,如下所示。

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

我这里没有那些 JS 变量。到目前为止,我找不到任何适合我的解决方案。

这里是 plunk 的链接: http://plnkr.co/edit/ttaq0l3PDRu4piwSluUX?p=preview

【问题讨论】:

  • 请在此处(使用代码 sn-p 功能)或在 jsFiddle、Plunker 等上提供一个最小的工作示例。目前尚不清楚您的变量来自何处,因此您的问题不可能按现在的方式回答。
  • @Agop 添加了 plunk 的链接
  • 我不太明白你在问什么......

标签: javascript angularjs angular-ngmodel angularjs-ng-model


【解决方案1】:

在你的情况下,它看起来像这样:

<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

【讨论】:

    猜你喜欢
    • 2014-10-05
    • 2020-08-28
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    相关资源
    最近更新 更多