2016-05-31 34 views
0

有人可以指導我嗎?當我將$scope.nameStaff置於ng-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'。

相關問題