在一个HTML页面中使用多个表单,并在angularjs中获取两个表单的对象

时间:2016-11-18 11:16:28

标签: html angularjs

我的HTML代码是

    const animals = [
    {name: 'Zack', type: 'dog'},
  {name: 'Mike', type: 'fish'},
  {name: 'Amy', type: 'cow'},
  {name: 'Chris', type: 'cat'},
  {name: 'Zoe', type: 'dog'},
  {name: 'Nicky', type: 'cat'},
  {name: 'Cherry', type: 'dog'}
]

let dogs = [];
function getDogs() {
    //return only dogs
  animals.map((animal) => {
    if(animal.type === "dog") {
      dogs.push(animal);
    }
  });
}
getDogs();

let dogsAmt = 0;
function getDogsAmt() {
    //get dogs amount
    dogsAmt = dogs.length;
}
getDogsAmt();

function updateDogsAmt() {
  //update dom with dogs count
  let dogsHTML = document.getElementById('dogs-amt');
  dogsHTML.innerHTML = dogsAmt;
}
updateDogsAmt();

let otherAnimals = [];
function getOtherAnimals() {
    //return other animals count 
  animals.map((animal) => {
    if(animal.type != "dog") {
      otherAnimals.push(animal);
    }
  });
}
getOtherAnimals();

let otherAnimalsAmt = 0;
function getOtherAnimalsAmt() {
    otherAnimalsAmt = otherAnimals.length;  
}
getOtherAnimalsAmt();

function updateOtherAnimalsAmt() {
    //udate dom with other animals
  let otherAmt = document.getElementById('other-amt');
  otherAmt.innerHTML = otherAnimalsAmt;
}
updateOtherAnimalsAmt();

并且在我的控制器中我使用scope.controller访问表单看起来像

<div>
<div>
<form name="form 1" ng-submit="submitForm1()">
<input type="text" required name="text1">
</form>
</div
<div>
<form name="form 2" ng-submit="submitForm2()">
<input type="text" required name="text2">
</form>
</div>
</div>

但是在结果中,第一个表单将给出对象,第二个表单将返回undefined 我明白为什么会这样。

2 个答案:

答案 0 :(得分:1)

您必须将ngModel用于每个表单中的字段才能访问数据。 https://docs.angularjs.org/api/ng/directive/ngModel

<form name="firstForm" ng-submit="submitForm1()">
    <input type="text" required name="text1" ng-model="firstForm.text1>
</form>

<form name="secondForm" ng-submit="submitForm2()">
    <input type="text" required name="text1" ng-model="secondForm.text1>
</form>

在控制器中

$scope.firstForm.text1 to access the data from first form individually.
$scope.secondForm.text1 to access the data from second form individually.

要获取完整的表单对象,请使用。

$scope.firstForm;
$scope.secondForm;

答案 1 :(得分:0)

从表单名称中删除空格。

<!-- remove spaces from form name
<form name="form 1" ng-submit="submitForm1()">
-->
<form name="form1" ng-submit="submitForm1()">
<input type="text" required name="text1" ng-model="a">
</form>
<!-- remove spaces from form name
<form name="form 2" ng-submit="submitForm2()">
-->
<form name="form2" ng-submit="submitForm2()">
<input type="text" required name="text2" ng-model="b">
</form>

导致$ parse错误。

DEMO on JSFiddle