2016-05-31 1 views
0

誰かが私を案内できますか? $scope.nameStaffng-repeatに入れると、その値はundefinedになります。私はなぜ値がundefinedであるのか分からない。

これは私のコードです:

<div ng-controller="MyCtrl"> 
<div ng-repeat="form in form"> 
<input type="text" ng-model="nameStaff" /> 
<input type="text" ng-model="idStaff" /> 
<button ng-click=addDetail()>add 
</button>1 
</div> 
{{form}} 
</div> 



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

function MyCtrl($scope) { 
    $scope.form = [{ 
    companyName: "company1", 
    companyAddress: "company address", 
    staff: [{ 
     name: "men", 
     id: "123" 
    }] 
    }, { 
    companyName: "company1", 
    companyAddress: "company address", 
    staff: [{ 
     name: "men", 
     id: "123" 
    }] 
    }] 
    $scope.addDetail = function() { 
    alert($scope.nameStaff); 
    $scope.form[0].staff.push({ 
     name: $scope.nameStaff, 
     id: $scope.idStaff 
    }); 
    } 
} 
+1

[ngRepeatのドキュメント](https://docs.angularjs.org/api/ng/directive/ngRepeat)を確認してください。 'ngRepeat'の各ループは独自のスコープを取得します。これが当てはまらない場合、 'addDetail'メソッドはあなたが参照していた' nameStaff'をどのように知っていますか? – Lex

答えて

1

これは、あなたが(私はあなたがこれをしたいと思う理由はわかりません、が)何をしたいです:

<!-- don't refer to children with the same name as parents --> 
<div ng-repeat="f in form"> 
    Staff Name: 
    <input type="text" ng-model="f.staff.name" /> <br /> 
    Staff Id: 
    <input type="text" ng-model="f.staff.id" /> 
    <button type="button" ng-click="addStaff(f.staff)" /> 
</div> 

Javascriptを:

$scope.addStaff = function(staff) { 
    var staffName = staff.name; 
    var staffId = staff.id; 
} 
+0

ありがとう..助けてください.. –

0

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

 
function MyCtrl($scope) { 
 
    $scope.form = [{ 
 
     companyName: "company1", 
 
     companyAddress: "company address", 
 
     staff: [{ 
 
      name: "men", 
 
      id: "123" 
 
     }] 
 
    }, { 
 
     companyName: "company1", 
 
     companyAddress: "company address", 
 
     staff: [{ 
 
      name: "men", 
 
      id: "123" 
 
     }] 
 
    }] 
 
    $scope.addDetail = function() { 
 
     alert($scope.nameStaff); 
 
     $scope.form[0].staff.push({ 
 
      name: $scope.nameStaff, 
 
      id: $scope.idStaff 
 
     }); 
 
    } 
 
} 
 

 
myApp.controller('MyCtrl', MyCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
    <div ng-repeat="f in form"> 
 
     <input type="text" ng-model="$parent.nameStaff" /> 
 
     <input type="text" ng-model="$parent.idStaff" /> 
 
     <button ng-click=addDetail()>add 
 
     </button> 
 
    </div> 
 
    {{form}} 
 
</div>

「$ parent.nameStaff」を使用できます。

関連する問題