2015-07-10 43 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