在 Angularjs 中添加具有不同值的新 HTML 内容

Add new HTML content with different values in Angularjs

我创建了一个指令来在单击按钮 "add" 时添加一些内容。但是我不知道如何获取这些新输入中的所有值。

HTML代码

angular.module('myApp', [])
  .controller('myController', function() {

  })
  .directive('addContent', function($document, $compile) {
    return {
      restrict: 'A',
      replace: false,
      link: function(scope, element, attr) {
        element.on('click', function() {
          var newcontent = '<input type="text" ng-model="myModel"><br>';
          angular.element($document[0].querySelector('.newcontent')).append($compile(newcontent)(scope));
        })
      }
    }

  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="newcontent" ng-app="myApp" ng-controller="myController">
  <button type="button" add-content>Add</button><br><br>
</div>

那么,如何为创建的每个新输入设置不同的 ng-model 值,以及如何在我的控制器中获取这些值?

你可以这样选择:

想法:

  • 可以从应用指令的 html 定义基本名称。
  • 创建新输入时在指令中使用增量数字(使用此模型的视图控制器(程序员)必须知道这一点)。实际上,在这种情况下,您可以使用您更喜欢的任何其他策略。为了简单起见并说明我的观点,我使用了这个。

代码(见下面的片段):

指令中

  • 创建一个随着新输入的增加而递增的计数器:var count = 0;
  • 取html中指定的基名与var model = scope.$eval(attr['addContent']);
  • 修改 newcontent 变量以使用该基本名称和增量计数器,如下所示:var newcontent = '<input type="text" ng-model="' + model + (count++) + '"><br>';

控制器

  • 为了组织,创建一个变量来保存基本名称:$scope.buttonModel = 'buttonModelReference';
  • 像这样访问这些新模型的值:$scope[$scope.buttonModel + $scope.index] 其中 $scope.index 是输入的索引(其中 0 是创建的第一个输入)

风景

  • 像这样使用修改后的指令 add-content="buttonModel" 其中 buttonModel 是控制器中定义的变量。

加码(仅供演示)

  • showModel 函数显示一个(动态创建的)输入的值作为参考传递输入的索引(0 零是创建的第一个输入的索引)

片段

angular.module('myApp', [])
  .controller('myController', function($scope) {

    $scope.index;
    $scope.buttonModel = 'buttonModelReference';

    $scope.showModel = function() {
      console.log($scope[$scope.buttonModel + $scope.index]);
    }

  })
  .directive('addContent', function($document, $compile) {
    var count = 0;
    return {
      restrict: 'A',
      replace: false,
      link: function(scope, element, attr) {
        element.on('click', function() {
          var model = scope.$eval(attr['addContent']);
          var newcontent = '<input type="text" ng-model="' + model + (count++) + '"><br>';
          angular.element($document[0].querySelector('.newcontent')).append($compile(newcontent)(scope));
        })
      }
    }

  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="newcontent" ng-app="myApp" ng-controller="myController">
  <button type="button" ng-click="showModel()">showModel</button> &nbsp; <input ng-model="index" type="number" placeholder="select the model index starting from 0" /> <br><br>
  <button type="button" add-content="buttonModel">Add</button><br><br>
</div>