如何使用ng-switch添加许多字段(angularjs)

时间:2015-06-20 19:15:43

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat angularjs-ng-switch

我有两个嵌套的ng-repeat,我想多次添加相同的表单 MiseEnContext ,在这个" MiseEncontext"我想添加一些输入,但当我添加文本时,它已添加到我的所有 MiseEnContext 题: 如何隔离我的 MiseEncontext

'<h4>Exercice Redactionnel</h4>\
                    <ul>\
                        <li><a ng-click="addMiseEnContext()">Mise en context</a></li>\
                        <li><a ng-click="addQuestion()">Question</a></li>\
                    </ul>\
                    <div ng-repeat="exRedContent in exRedContents">\
                        <div ng-switch on={{exRedContentType}}>\
                            <div ng-switch-when="1">\
                                <h5>Mise en context</h5>\
                                    Titre<input type="text" /><br />\
                                        <button ng-click="addTexte(1)">addText</button>\
                                    <div ng-repeat="MecField in MecFields">\
                                        <div ng-switch on={{fieldsType}}>\
                                                <div ng-switch-when="1">\
                                            Text<input type="text">\
                                        </div>\
                                            <div ng-switch-when="2">\
                                                  <h5>Text illustré</h5></ br>\
                                                  Position: <input type="radio" name="group1" value="droit" checked>Text à droite<br />\
                                            </div>\
                                     </div>\
                            </div>\
                          </div>\
                        <div ng-switch-when="2">\
                                <h5>Question</h5>\
                            </div>\
                    </div>\
                  </div>'

演示:http://plnkr.co/edit/Cr0WN4hCuKTYJOfb5CBf?p=preview

1 个答案:

答案 0 :(得分:1)

您的问题是您在指令中使用$scope.MecFields作为共享能力$scope变量。我希望通过向该对象添加索引来使其分离,以便它将成为每个ng-repeat元素的唯一/单独数组。数组内容将取决于索引。

<强>标记

<button ng-click="addTexte($index)">addText</button>\
<div ng-repeat="MecField in MecFields[$index]">\
    <div ng-switch on={{fieldsType}}>\
        <div ng-switch-when="1">\ Text
            <input type="text">\
        </div>\
        <div ng-switch-when="2">\
            <h5>Text illustré</h5></ br>\ Position:
            <input type="radio" name="group1" value="droit" checked>Text à droite
            <br />\
        </div>\
    </div>\
</div>\

<强>代码

$scope.addTexte = function(index) {
  $scope.fieldsType = $scope.types[0].id;
  if (!$scope.MecFields[index]) $scope.MecFields[index] = [];
  $scope.MecFields[index].push({
    field: '',
    value: ''
  });
};

Demo Plunkr