如何在AngularJS中推送新模板,每次都会渲染旧模板

时间:2018-05-03 22:21:29

标签: angularjs

我正在尝试将新模板推送到我的DOM中,但每次我都会获得以前模板的副本。如何推送新的模板副本

  $scope.addNew = function (personalDetail) {
                $scope.personalDetails.push({
                    'add_template': '<div my-custom-row-template> </div>',
                });
            };
            $scope.conditions = [];
            $scope.conditions.push('myCustomRowTemplate');
            $scope.addCondition = function () {
                $scope.conditions.push('myCustomRowTemplate');
            };

这是在HTML文件中呈现的方式。

 <tr ng-repeat="personalDetail in personalDetails">
     <td scope="col">
     <input type="checkbox" ng-model="personalDetail.selected"/>
     </td>
     <td scope="col" class="col-xs-10">
     <div ng-repeat="condition_set in conditions track by $index" my-custom-row-template></div>
      </td>
       </td>
       <td scope="col">
       <input type="button" value="Add Condition" ng-click="addCondition()"
                                                       class="btn btn-primary addnew"/>
       </td>
      </tr>

1 个答案:

答案 0 :(得分:1)

不确定你想要在这里实现什么,所以我可能会离开,但问题是你每次调用这些函数时都在推新模板:

  //Calling addNew() - will add to personalDetails array again every click
  $scope.addNew = function (personalDetail) {
                //You can add:
                $scope.personalDetails = [];

                $scope.personalDetails.push({
                    'add_template': '<div my-custom-row-template> </div>',
                });
            };
            //$scope.conditions = []; - move it inside the function
            $scope.conditions.push('myCustomRowTemplate');

            //Same with this function - each time it is called you are pushing a new condition, you should clear that too
            $scope.addCondition = function () {
                $scope.conditions = [];
                $scope.conditions.push('myCustomRowTemplate');
            };

如果您希望将此模板作为“默认”,则应将其移至这些函数之外并将其置于新函数上,并使用ng-init或类似函数调用它。

编辑:

现在看完这个例子之后,我理解了这个问题 - 你在条件中使用了相同的范围变量,所以它们是重复的。

您应该添加如下属性:

$scope.addNew = function() {
          $scope.personalDetails.push({
          'add_tempalte': '<div my-custom-row-template> </div>',
        });
        };

        $scope.addCondition = function(personalDetail) {
         personalDetail.conditions = personalDetail.conditions||[]; //init new array if needed
         personalDetail.conditions.push('myCustomRowTemplate');
        };