我正在尝试实现一个更新表单,但是当我点击提交按钮时,我经常遇到这个错误:
TypeError: Cannot read property '1' of undefined
这是我的 Controller :
$scope.pets = [];
$http.get(baseApiUrl + '/pets').
success(function (data) {
console.log("Success : " + data);
$scope.pets = data;
}).error(function () {
console.log(data);
});
$scope.UpdateData = function (index) {
$http({
method: 'PUT',
url: baseApiUrl + '/pets/' + index,
data: {
id: index,
name: $scope.updateName[index],
age: $scope.updateAge[index],
owner: $scope.updateOwner[index],
}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
这是我的观点:
<tbody>
<tr ng-repeat="pet in pets track by pet.id">
<td><input type="text" placeholder="{{ pet.name }}" name="name" class="form-control" ng-model="updateName[pet.id]" required></td>
<td><input type="text" placeholder="{{ pet.age }}" name="age" class="form-control" ng-model="updateAge[pet.id]" required></td>
<td><input type="text" placeholder="{{ pet.owner }}" name="owner" class="form-control" ng-model="updateOwner[pet.id]" required></td>
<td><input id="update" type="submit" class="btn btn-danger disabled" ng-click="UpdateData(pet.id)" /></td>
</tr>
</tbody>
我找不到为什么这不起作用。如果您有任何建议。谢谢
最佳答案
我问了一个与此主题相关的问题(但在 C# 中)Create dynamic variable name 请检查问题和答案。希望对您有所帮助。
对于我们不能在 C# 中创建动态变量,有一个答案。就像我们不能在 angularjs 中创建任何动态模型名称一样。
但在这种情况下,我们可以在 array(pets)
中动态创建一个新的对象名称。
请尝试以下方式
You need to change
ng-model="pet.updateAge[pet.id]"
tong-model="pet.updateAge"
and you can pass the pet object to your submit method via paramng-click="UpdateData(pet)"
<tr ng-repeat="pet in pets track by pet.id">
<td>
<input type="text" placeholder="{{ pet.name }}"
name="name" class="form-control" ng-model="pet.updateName"
required>
</td>
<td>
<input type="text" placeholder="{{ pet.age }}"
name="age" class="form-control" ng-model="pet.updateAge"
required>
</td>
<td>
<input type="text" placeholder="{{ pet.owner }}"
name="owner" class="form-control" ng-model="pet.updateOwner"
required>
</td>
<td>
<input id="update" type="submit" class="btn btn-danger disabled"
ng-click="UpdateData(pet)" /></td></tr>
And you can get the values from the method param and you can use that as the below way
$scope.UpdateData = function (pet) {
$http({
method: 'PUT',
url: baseApiUrl + '/pets/' + pet.id,
data: {
id: pet.id,
name: pet.updateName,
age: pet.updateAge,
owner: pet.updateOwner,
}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
关于javascript - 更新表单时无法读取 angularjs 中未定义的属性 '1',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44651356/