2015-07-10 60 views
0

我有一个模板与文本框在我的指令,点击按钮(ADD)我重复相同的指令10倍,所以10倍的文本框会来,但NG模型将对于每个文本框都保持不变,并且我需要进行动态化处理,以便模板ng-model的每次重复都变得不同。 问题是我无法创建文本框的动态ng模型来区分输入的值,以便我可以在我的控制器中访问它。如何使文本框的模型动态化。如何在我的模板中动态模型angularjs

App.directive("configDirectives", function($compile) { 
 
     return { 
 
     restrict: 'EA', 
 
     link: function(scope, element, $attr) { 
 
      console.log('Scope in directive : ' + scope); 
 
      scope.add = function() { 
 
      console.log("Inside directive value of satCount", satCount++); 
 
      $newDirective = angular.element('<add-config></add-config>'); 
 
      element.append($newDirective); 
 
      $compile($newDirective)(scope); 
 
      console.log('Scope in directive : ' + scope); 
 
      } 
 
     } 
 
     }).directive("addConfig", function() { 
 
     return { 
 
      restrict: 'AE', 
 
      template: '<div>{{scope.satCount}}' + 
 
      '<input type="text" ng-model="x"/>' + 
 
      '</div>', 
 
      link: function(scope, element, attribute) { 
 
      scope.remove = function() { 
 
       element.remove(); 
 
      } 
 
      } 
 
     }); 
 
     <!-- Controller --> 
 
     (function() { 
 
     var self = null; 
 
     var ConfigRuleClass = Class.extend({ 
 
      init: function($scope, configService) { 
 
      self = this; 
 
      self.$scope = $scope; 
 
      }, 
 
      save: function() { 
 
      console.log("values from parent configuration---"); 
 
      console.log("config1---", self.lstConfigs.name); 
 
      console.log("Dynamic Filed Data" + self.dynamicConfigs); 
 

 
      } 
 
     }); 
 
     App.controller("ConfigRuleCntrl", ['$scope', 'configService', ConfigRuleClass]); 
 
     })();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div id="xx" data-ng-controller="ConfigRuleCntrl as y"> 
 
    <input type="text" ng-model="y.x" /> 
 
    <button data-ng-click="add()">Add</button> 
 
    <br> 
 
    <button data-ng-click="y.save()">SAVE</button> 
 
    <config-directives></config-directives> 
 
</div>

+0

你能为你的问题创造plnkr? – dhavalcengg

+0

你如何重复文本框? – dfsq

+0

应该是我们在这里失踪的ng-repeat?点击按钮(ADD) – n00b

回答

0

您可以创建10个对象的数组和源NG重复使用。
对象将是这样的:

[ 
    { id:1 value:'' }, 
    { id:2 value:'' }, 
    ... 
] 

和HTML:

<input type="text" ng-repeat="entry in entries track by entry.id" ng-model="entry.value"></input> 

我创建了一个的jsfiddle展示它是如何工作的: http://jsfiddle.net/un1g3fao/2/

+0

我无法使用ng-repeat,因为点击时我只想重复我的模板一次,所以我需要解决方案而不使用ng-repeat。 –

+0

然后,您只需将1个条目添加到重复来源即可。或者,如果这不合适,请包括一名笨蛋来显示您的具体问题。 –

+0

如果要求是100次,该怎么办?我只能重复使用我的模板时,我不能在点击时使用ng-repeat。非常感谢您的回复 –

0

试试这个代码在使用创建一个动态模型input

Working Code Clck Here

<input type="text" ng-model="newObject[item.name]"> 

保持了以往使用数据复制

var original = Data.data; 
$scope.newObject =angular.copy(original); 
+0

我同意你的解决方案,但我必须重复我的模板点击,每次点击只有一次,我也必须保持以前的数据。所以我不能使用ng-repeat。非常感谢你的回复 –

+0

你肯定*可以*使用'ng-repeat';把你的数据放到一个数组中,并且每当你想添加一个新行时,向该数组添加一个新元素。其余的角落会做。 – Claies