将 ng-model 值动态设置为 AngularJS 中 js 变量的值
Setting ng-model value dynamically to the value of js variable in AngularJS
以前有人问过类似的问题,我也试过给他们的解决方案,但我的问题有点不同。
假设我的控制器中有一组这样的对象
$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
值设置为 placeholder1
和 placeholder2
而不是像 field.field_name
这样的 javascript
变量,因为我的目标来自另一个包含 html 的来源,如下所示。
<p>this is sample html {{placeholder1}}. again sample html {{placeholder2}} </p>
我这里没有那些 JS 变量。到目前为止,我找不到任何适合我的解决方案。
这里是 link 要插入的内容:
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
每次迭代都会创建子作用域,因此您需要更上一层楼。
以前有人问过类似的问题,我也试过给他们的解决方案,但我的问题有点不同。
假设我的控制器中有一组这样的对象
$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
值设置为 placeholder1
和 placeholder2
而不是像 field.field_name
这样的 javascript
变量,因为我的目标来自另一个包含 html 的来源,如下所示。
<p>this is sample html {{placeholder1}}. again sample html {{placeholder2}} </p>
我这里没有那些 JS 变量。到目前为止,我找不到任何适合我的解决方案。
这里是 link 要插入的内容: 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
每次迭代都会创建子作用域,因此您需要更上一层楼。