【问题标题】:How to dynamically add ng-model name to template added dinamically with ng-repeat and button click?如何将 ng-model 名称动态添加到使用 ng-repeat 和按钮单击动态添加的模板中?
【发布时间】:2019-07-14 19:42:17
【问题描述】:

我有一个模板 app/views/templates/destForm.tpl.html

<div class="row">
   <div class="col-sm-8">
      <div class="form-group">
         <label>Departure</label>
         <input class="form-control form-control-rounded input-lg" type="text" ng-model="???????" />
      </div>
   </div>
</div>

我将它包含在我的 html 页面中,如下所示:

<form action="" name="formPackages">
    <div ng-repeat="form in destForms track by $index">
        <dest-form></dest-form>
    </div>
...

在我的控制器中,我有这个代码:

$scope.destForms = [];
$scope.addForm = function(){
    var formIndex = $scope.destForms.length + 1;
    $scope.destForms.push('app/views/templates/destForm.tpl.html');
}

$scope.addForm();

编辑 1:(建议在 cmets 中)

这是我的指令。

function destForm () {
    return {
        restrict: 'E',
        transclude: true,
        scope: {
          ngModel: '<'
        },
        bindToController: true,
        controllerAs: '$quoteAskCtrl',
        templateUrl: 'app/views/templates/destForm.tpl.html',
        controller: 'quoteAskCtrl'
    };
}

编辑 2 如何将模板 html 中的 ng-model 设置为在我的控制器的 $scope 中可用?用户可以选择只离开一次或多次,这就是我动态添加的内容

编辑 3 这就是我想要达到的目标,所以当提交表单时,我需要在这个出发目的地循环以将它们发布到我的数据库。

我正在尝试为用户必须进行的每个“出发”添加一个模板。 如何动态添加 ng-model 以便我可以在控制器中收集数据以制作 $http.post?

提前致谢。

【问题讨论】:

标签: html angularjs angular-template


【解决方案1】:

在你的指令中:

<input class="form-control form-control-rounded input-lg" type="text" ng-model="$quoteAskCtrl.ngModel" />

和你的 html:

<form action="" name="formPackages">
   <div ng-repeat="form in destForms track by $index">
   <dest-form ng-model="form"></dest-form>
</div>

解释: 您的指令期望从父对象接收属性为“ngModel”。

因为你已经设置了:controllerAs: '$quoteAskCtrl', 需要这样访问:ng-model="$quoteAskCtrl.ngModel"

【讨论】:

  • 哦。我觉得这就是。我会尽力让你知道。谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多