使用AngularJs将ng-model指令添加到动态创建的输入标记中

时间:2017-06-07 11:12:01

标签: angularjs

我正在尝试按下按钮,创建div和输入标签,输入标签包含ng-model,div与该输入绑定。 请提出一些解决方案。

4 个答案:

答案 0 :(得分:0)

您可以事先创建divinput,但不要使用ng-if="myVar"来展示它。点击后点击ng-if="true"

<button ng-click="myVar = true">

在控制器中:$scope.myVar = false;

答案 1 :(得分:0)

$scope.addInputBox = function(){    
//#myForm id of your form or container boxenter code here
$('#myForm').append('<div><input type="text" name="myfieldname" value="myvalue" ng-model="model-name" /></div>');
}

答案 2 :(得分:0)

您应该使用$compile service将范围和模板链接在一起:

&#13;
&#13;
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', '$compile', '$document' , function MyCtrl($scope, $compile, $document) {
  var ctrl = this;

  var inputTemplate = '<div><span ng-bind="$ctrl.testModel"></span>--<span>{{$ctrl.testModel}}</span><input type="text" name="testModel"/></div>';
 
  ctrl.addControllDynamically = addControllDynamically;

  var id = 0;
  function addControllDynamically() {
    var name = "testModel_" + id; 
    var cloned = angular.element(inputTemplate.replace(/testModel/g, name)).clone();
    cloned.find('input').attr("ng-model", "$ctrl." + name); //add ng-model attribute
    $document.find('[ng-app]').append($compile(cloned)($scope)); //compile and append
    id++;
  }

  return ctrl;
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">
    <input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
  </div>
</div>
&#13;
&#13;
&#13;

更新:每次点击按钮时添加新的已编译模板,我们需要制作clone of the element

更新2:上面的示例表示从控制器操纵DOM的脏方法,should be avoided。更好( angular - )解决问题的方法是使用自定义模板创建一个指令,并将其与ng-repeat一起使用,如下所示:

&#13;
&#13;
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
  var ctrl = this;

  ctrl.controls = [];
  ctrl.addControllDynamically = addControllDynamically;
  ctrl.removeControl = removeControl;
  
  function addControllDynamically() {
    //adding control to controls array
    ctrl.controls.push({ type: 'text' });
  }
  
  function removeControl(i) {
    //removing controls from array
    ctrl.controls.splice(i, 1);
  }

  return ctrl;
}])
.directive('controlTemplate', [function () {
        var controlTemplate = {
            restrict: 'E',
            scope: {
              type: '<',
              ngModel: '='
            },
            template: "<div>" +
              "<div><span ng-bind='ngModel'></span><input type='type' ng-model='ngModel'/></div>" +
              "</div>"
        }
        return controlTemplate;
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">
    <input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
    
    <div ng-repeat="control in $ctrl.controls">
      <control-template type="control.type" ng-model="control.value"></control-template>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这是另一种解决方案,其中不需要明确地创建const stream = require('stream'); function getPrimesStream(n, cb) { const primesStream = new stream.Stream(); cb(null, primesStream); if (n >= 2) { primesStream.emit('data', 2); } const primes = [2]; for (let i = 3; i < n; i += 2) { let isPrime = true; const sq = Math.ceil(Math.sqrt(i)); for (let t = 2; t <= sq; t += 1) { if (i % t === 0) { isPrime = false; break; } } if (isPrime) { primesStream.emit('data', i); primes.push(i); } } return primes; } getPrimesStream(1000, function (err, stream) { stream.on('data', function (data) { console.log(data); }); stream.on('end', function() { console.log('finished'); }); }); div。使用input循环遍历元素数组。优点是您将拥有该数组中ng-repeat的所有值。

&#13;
&#13;
inputs
&#13;
angular.module('app', [])
.controller('AppController', AppController);

AppController.$inject = ['$scope'];
function AppController($scope) {
  $scope.values = [];
  $scope.add = function() {
    $scope.values.push('');
  };
}
&#13;
&#13;
&#13;

更新。如果您只需要一个输入,那么使用<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="AppController"> <button ng-click="add()">Click</button> <div ng-repeat="value in values track by $index"> <input type="text" ng-model="values[$index]"/> <div>{{values[$index]}}</div> </div> <pre>{{values}}</pre> </div>就更简单了。

&#13;
&#13;
ng-show
&#13;
angular.module('app', []);
&#13;
&#13;
&#13;