2017-01-16 14 views
0

Я работаю над угловым проектом. У меня есть два div. В одном div есть динамический ввод, который генерируется через ng-repeat. Изначально два входа будут доступны, но если euser нажимает на добавление более динамических двух входных данных, будет генерироваться через ng-repeat. И в другом div есть два текста типа ввода, которые уже присутствуют там (не генерируются через ng-repeat).Как получить данные в контроллере как поля ng-repeat, так и внешнего поля ng-repeat

Проблема, с которой я столкнулся, - как принять значение обоих входных данных div на submit.Pls, помогите мне в этом, как взять все данные сразу на submit. Мой код:

var addnew = angular.module('dump',[]); 
 

 
addnew.controller('dumpcontroller', function($scope) 
 
{ 
 
    $scope.choices = [{id: 'choice1'}]; 
 
    $scope.addNewChoice = function() { 
 
    var newItemNo = $scope.choices.length+1; 
 
    $scope.choices.push({'id':'choice'+newItemNo}); 
 
    }; 
 

 

 
    $scope.removeChoice = function() { 
 
     var lastItem = $scope.choices.length-1; 
 
     $scope.choices.splice(lastItem); 
 
    }; 
 
    });
<html> 
 
    <head> 
 
    <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> 
 
    </head> 
 
<body ng-app="dump" ng-controller="dumpcontroller">  
 
<div class="divone" data-ng-repeat="choice in choices"> 
 
    <input type="text" placeholder="Name" ng-model="choice.childname"> 
 
    <input type="text" placeholder="Name" ng-model="choice.childbirth"> 
 
    <button ng-click="removeChoice()">-</button> //To remove the field dynamically. 
 
</div> 
 

 
<button class="remove" ng-click="addNewChoice()">Add more</button> //To add the more childname and childbirth field. 
 

 
<div class="divtwo"> 
 
    <input type="text" placeholder="Name" ng-model="choice.firstname"> 
 
    <input type="text" placeholder="Name" ng-model="choice.lastname"> 
 
</div> 
 

 
<button type="button" id="submit" name="submit" ng-click="famupdate(choices)">Submit</button> 
 
    
 
    </body> 
 
    </html>

Теперь я хочу, чтобы получить все детали как DIV на клик в controller.How я могу добиться этого. Выручи меня.

Спасибо вам в ожидании.

+0

Поделитесь своим кодом в plnkr. –

+0

Я добавил фрагмент – Mohammed

+0

вы хотите как в том же массиве? –

ответ

1

начало ng-repeat от пользовательского смещения, так что вы получите как в одном массиве

<div ng-repeat="choice in choices | limitTo: (1 - choices.length)"> 
.... 
</div> 
<div class="divtwo"> 
    <input type="text" placeholder="Name" ng-model="choices[0].firstname"> 
    <input type="text" placeholder="Name" ng-model="choices[0].lastname"> 
</div> 

подробный пример приведен в скрипку check this out

0

Если возможно, пришлите мне ур полный код (код js) .or share ur js fiddle.I изменится и поделитесь с u.

<div class="divone" data-ng-repeat="choice in choices track by $index"> 
    <input type="text" placeholder="Name" ng-model="choice.childname[$index]"> 
    <input type="text" placeholder="Name" ng-model="choice.childbirth[$index]"> 
    <button ng-click="removeChoice()">-</button> //To remove the field  dynamically. 
</div> 

<button class="remove" ng-click="addNewChoice()">Add more</button> //To add the more childname and childbirth field. 

<div class="divtwo"> 
    <input type="text" placeholder="Name" ng-model="choice.firstname"> 
    <input type="text" placeholder="Name" ng-model="choice.lastname"> 
</div> 

<button type="button" id="submit" name="submit" ng-click="famupdate(choices,$index)">Submit</button> 

var counter = 0; 
$scope.choices = []; 

for (var choice in $scope.choices) { 
    var firstName = choice.firstName; 
    var lastName = choice.lastName; 
    var childname = choice.childName[counter]; 
    var childbirth = choice.childbirth[counter]; 
    counter++; 
} 

$scope.addNewChoice = function() { 
    var obj = {'childName':'','childbirth':''} 
    $scope.choices.push(obj) 
} 
+0

PLS см. Сниппет. Я добавил логику динамического повторения ввода. Я хочу, чтобы логика получала все значение поля ввода. Благодарю. – Mohammed

0

Одна вещь, которую я наблюдал это вы принимаете "choice.firstname" в #div2, но собирая выбор. Чтобы сделать его более простым, я взял две разные модели для сбора данных, а затем объединил их. Попробуйте ниже

var addnew = angular.module('dump',[]); 
 

 
addnew.controller('dumpcontroller', function($scope) 
 
{ 
 
    $scope.choices = [{id: 'choice1'}]; 
 
    $scope.addNewChoice = function() { 
 
    var newItemNo = $scope.choices.length+1; 
 
    $scope.choices.push({'id':'choice'+newItemNo}); 
 
     
 
    }; 
 

 
    $scope.removeChoice = function() { 
 
     var lastItem = $scope.choices.length-1; 
 
     $scope.choices.splice(lastItem); 
 
    }; 
 
    
 
    $scope.famupdate = function (choices,choices2) { 
 
    choices.push(choices2); 
 
    console.log(choices); 
 
    }; 
 
    
 
});
<html> 
 
    <head> 
 
    <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> 
 
    </head> 
 
<body ng-app="dump" ng-controller="dumpcontroller">  
 
<div class="divone" data-ng-repeat="choice in choices track by $index"> 
 
    <input type="text" placeholder="Name" ng-model="choices[$index].childname"> 
 
    <input type="text" placeholder="Name" ng-model="choices[$index].childbirth"> 
 
    <button ng-click="removeChoice()">-</button> //To remove the field dynamically. 
 
</div> 
 

 
<button class="remove" ng-click="addNewChoice()">Add more</button> //To add the more childname and childbirth field. 
 

 
<div class="divtwo"> 
 
    <input type="text" placeholder="Name" ng-model="choices2.firstname"> 
 
    <input type="text" placeholder="Name" ng-model="choices2.lastname"> 
 
</div> 
 

 
<button type="button" id="submit" name="submit" ng-click="famupdate(choices,choices2)">Submit</button> 
 
    
 
    </body> 
 
    </html>

1

То, что вы должны сделать, это просто использовать $scope.choice объект в функции мыши. Я внес некоторые изменения в ваш код. При добавлении нового объекта в объект я инициализировал их нулевой строкой. Кроме того, инициализированный ng-model для второго div немного запутан, используя choice.firstname и choice.lastname. Я заменил их только firstname и lastname. Посмотрите на этот код.

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 
    <script> 
 
     var addnew = angular.module('dump', []); 
 
     addnew.controller('dumpcontroller', function ($scope) { 
 
      $scope.choices = [{ 
 
       id: 'choice1' 
 
      }]; 
 
      $scope.addNewChoice = function() { 
 
       var newItemNo = $scope.choices.length + 1; 
 
       $scope.choices.push({ 
 
        'childname': "", 
 
        'childbirth': "" 
 
       }); 
 
      }; 
 
      $scope.removeChoice = function() { 
 
       var lastItem = $scope.choices.length - 1; 
 
       $scope.choices.splice(lastItem); 
 
      }; 
 
      
 
      $scope.famupdate = function (choices){ 
 
       //No need to pass choices object actually. You can just use $scope.choices also. 
 
       console.log("Data Generated Dynamically"); 
 
       console.log(choices); 
 
       console.log("Data value in second div"); 
 
       console.log($scope.firstname); 
 
       console.log($scope.lastname); 
 
      } 
 
     }); 
 
    </script> 
 
</head> 
 

 
<body ng-app="dump" ng-controller="dumpcontroller"> 
 
    <div class="divone" data-ng-repeat="choice in choices"> 
 
     <input type="text" placeholder="Name" ng-model="choice.childname"> 
 
     <input type="text" placeholder="Name" ng-model="choice.childbirth"> 
 
     <button ng-click="removeChoice()">-</button> //To remove the field dynamically. 
 
    </div> 
 

 
    <button class="remove" ng-click="addNewChoice()">Add more</button> //To add the more childname and childbirth field. 
 

 
    <div class="divtwo"> 
 
     <input type="text" placeholder="Name" ng-model="firstname"> 
 
     <input type="text" placeholder="Name" ng-model="lastname"> 
 
    </div> 
 

 
    <button type="button" id="submit" name="submit" ng-click="famupdate(choices)">Submit</button> 
 

 
</body> 
 

 
</html>

1

Вот ответ, изменение в соответствии с вашими требованиями.

var addnew = angular.module('dump',[]); 
 

 
addnew.controller('dumpcontroller', function($scope) 
 
{ 
 
    $scope.choices = [{id: 'choice1', 'childname':'', 'childbirth':'', 'firstname':'', 'lastname':''}]; 
 
    $scope.addNewChoice = function() { 
 
    var newItemNo = $scope.choices.length+1; 
 
    $scope.choices.push({'id':'choice'+newItemNo, 'childname':'', 'childbirth':'','firstname':'','lastname':''}); 
 
    }; 
 

 

 
    $scope.removeChoice = function() { 
 
     var lastItem = $scope.choices.length-1; 
 
     $scope.choices.splice(lastItem); 
 
    }; 
 
    $scope.famupdate = function(){ 
 
    console.log($scope.choices); 
 
    } 
 
    });
<html> 
 
    <head> 
 
    <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> 
 
    </head> 
 
<body ng-app="dump" ng-controller="dumpcontroller"> 
 
    <form name="sform"> 
 
<div class="divone" data-ng-repeat="choice in choices"> 
 
    <input type="text" placeholder="Name" ng-model="choice.childname"> 
 
    <input type="text" placeholder="Name" ng-model="choice.childbirth"> 
 
    <button class="remove" ng-click="addNewChoice()">Add more</button> //To add the more childname and childbirth field. 
 
    
 
    <a ng-click="removeChoice()">Remove</a> //To remove the field dynamically. 
 

 

 
<div class="divtwo"> 
 
    <input type="text" placeholder="FirstName" ng-model="choice.firstname"> 
 
    <input type="text" placeholder="LastName" ng-model="choice.lastname"> 
 
</div> 
 
</div> 
 
<button type="button" id="submit" name="submit" ng-click="famupdate(choices)">Submit</button> 
 
    </form> 
 
    {{choices}} 
 
    </body> 
 
    </html>

0

var addnew = angular.module('dump',[]); 
 

 
addnew.controller('dumpcontroller', function($scope) 
 
{ 
 
    $scope.choices = [{id: 'choice1'}]; 
 
$scope.choi = {}; 
 
    $scope.addNewChoice = function() { 
 
    var newItemNo = $scope.choices.length+1; 
 
    $scope.choices.push({'id':'choice'+newItemNo}); 
 
    }; 
 

 

 
    $scope.removeChoice = function() { 
 
     var lastItem = $scope.choices.length-1; 
 
     $scope.choices.splice(lastItem); 
 
    }; 
 

 
    $scope.famupdate = function(){ 
 
    for(var i=0;i<$scope.choices.length;i++){ 
 
    var childName = $scope.choices[i].childname; 
 
    var childbirth = $scope.choices[i].childbirth; 
 
    console.log('childName:',$scope.choices,childName,childbirth) 
 
    } 
 
    var firstName = $scope.choi.firstName; 
 
    var lastName = $scope.choi.lastName; 
 
    } 
 
    });
<html> 
 
    <head> 
 
    <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> 
 
    </head> 
 
<body ng-app="dump" ng-controller="dumpcontroller">  
 
<div class="divone" data-ng-repeat="choice in choices track by $index"> 
 
    <input type="text" placeholder="Name" ng-model="choice.childname"> 
 
    <input type="text" placeholder="Name" ng-model="choice.childbirth"> 
 
    <button ng-click="removeChoice()">-</button> //To remove the field dynamically. 
 
</div> 
 

 
<button class="remove" ng-click="addNewChoice()">Add more</button> //To add the more childname and childbirth field. 
 

 
<div class="divtwo"> 
 
    <input type="text" placeholder="Name" ng-model="choi.firstname"> 
 
    <input type="text" placeholder="Name" ng-model="choi.lastname"> 
 
</div> 
 

 
<button type="button" id="submit" name="submit" ng-click="famupdate(choices)">Submit</button> 
 
    
 
    </body> 
 
    </html>

+0

Он показывает ошибку. Пожалуйста, проверьте @ankit gupta – Mohammed

+0

, теперь он будет работать –