有没有一种方法可以使用angular中的$index作为ng重复中的模型

Is there a way to use $index in angular as the model in an ng-repeat?

本文关键字:ng 作为 index 模型 中的 angular 一种 可以使 方法 有没有      更新时间:2023-09-26

我有一个工厂,我正在将值从我的控制器推送到我的控制器。

.factory("Inputs", function(){
    var inputs = {
    };
    inputs.editors = [0];
    return inputs;
})

当我像一样循环时,我想使用$index作为模型

<div class="texteditors">
    <div class="form-group" ng-repeat="editor in app.inputs.editors">
        <textarea class="form-control" name="{{$index}}" ng-model="inputs.editors[{{$index}}]" id="" cols="30" rows="10"></textarea>
     </div>
</div>

但它不会评估,我唯一能让它评估的方法是这样的:

但现在它是一个字符串,它评估为输入。editors['0']

然后,我想循环遍历ng模型,并评估它们{{inputs.editors[0]}}添加了多少文本区域。我不确定我的解释是否正确。

如果我使用指令来创建绑定,我将如何评估通过将值推送到工厂而生成的文本区域和模型?

开始:

http://codepen.io/jlowcs/pen/ogJBVm

您的标记出现了一些问题。

您还需要将track by添加到ng-repeat,否则每次模型更改时都会失去焦点,因为文本区域是由ng-repeat重新创建的。

HTML:

<div class="texteditors" ng-controller="MyCtrl as app">
    <div class="form-group" ng-repeat="editor in app.inputs.editors track by $index">
        <textarea class="form-control" ng-model="app.inputs.editors[$index]" id="" cols="30" rows="10"></textarea>
    </div>
    <div class="form-group" ng-repeat="editor in app.inputs.editors track by $index">
        <div>{{app.inputs.editors[$index]}}</vid>
    </div>
</div>

JS:

app.controller('MyCtrl', function($scope, Inputs) {
    this.inputs = Inputs;
})
.factory("Inputs", function(){
    var inputs = {};
    inputs.editors = ['foo', 'bar'];
    return inputs;
})

处理字符串时只需要花括号。正如@DimaGimburg所说,在你的ngModel中去掉它们。

<div class="texteditors">
    <div class="form-group" ng-repeat="editor in app.inputs.editors">
        <textarea class="form-control" name="{{$index}}" ng-model="inputs.editors[$index]" id="" cols="30" rows="10"></textarea>
     </div>
</div>

ng-model需要一个角度表达式。这意味着您不需要{{}}表示法。

<textarea class="form-control" name="{{$index}}" ng-model="inputs.editors[$index]" id="" cols="30" rows="10"></textarea>

另一方面,name并不期望角度表达式。这就是为什么你需要{{}}