我有一个两层表,我想添加值。表格是动态加载的,当加载每个文本框时,我调用了一个函数,从两个 ng 重复发送项目,以便我可以检查它是哪个单元格文本框,如果存在它的值,则将其添加到 ng-model = result。该函数有效,但是,返回的值不会显示在文本框中。我不知道我做错了什么..这是我表的代码:
<div class="divTable">
<div class="divTableHeading">
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell" ng-repeat='item in TestingTable[1].EnvironmentTypes'>{{item.Name}}</div>
</div>
</div>
<div class="divTableBody">
<div class="divTableRow" ng-repeat='item in TestingTable[0].TestingType'>
<div class="divTableCell">{{item.Name}}</div>
<div class="divTableCell" ng-repeat="x in TestingTable[1].EnvironmentTypes">
<input type="text" ng-model="result" ng-init="result = loadData(x, $parent.item)">
</div>
</div>
</div>
</div>
还有我的 JavaScript 代码和 loadData 函数:
myApp.controller('ctrl', ['$scope', function($scope) {
var initial = 0;
$scope.TestingTable = [{
TestingType: [{
Id: 1,
Name: "Functional Testing"
},
{
Id: 2,
Name: "Regression Testing"
},
{
Id: 3,
Name: "Integration"
},
{
Id: 4,
Name: "BVT"
}
]
},
{
EnvironmentTypes: [{
Id: 1,
Name: "Dev/QE (VCD)"
},
{
Id: 2,
Name: "Staging"
},
{
Id: 3,
Name: "PPE"
},
{
Id: 4,
Name: "01's"
}
]
}
];
$scope.Testing = [{
Id: 1,
"TestingTypeId": 1,
TestingType: "Functional Testing",
EnvironmentTypeId: 1,
EnvironmentType: "Dev/QE (VCD)",
value: 100
},
{
Id: 2,
"TestingTypeId": 3,
TestingType: "Integration",
EnvironmentTypeId: 1,
EnvironmentType: "Dev/QE (VCD)",
value: 98
}
];
$scope.loadData = function(entype, type) {
if ($scope.Testing !== undefined) {
angular.forEach($scope.Testing, function(item) {
if (item.TestingTypeId === type.Id && item.EnvironmentTypeId === entype.Id) {
return item.Value;
} else {
return initial;
}
});
}
};
}]);
有人可以指出我做错了什么吗?
更新
这是我到目前为止点击的代码的 plunker
首先,您滥用了ng-init
,因为这是在ng-repeat
内执行的,因此每次您重新初始化result
模型时。您应该阅读更多有关ng-model
的信息,如果您为TestingType
和EnvironmentType
的每个组合都有一个Testing
,那将是一个很好的解决方案,但事实并非如此。
此外,您的loadData
函数不返回值。这些return
位于 forEach 的每次迭代执行的回调函数中,因此它们根本不返回 loadData 函数。
为了修复您的代码,我只是将ng-init
和ng-model
更改为我认为更适合这种情况的ng-value
:
<input type="text" ng-value="loadData(x, $parent.item)">
。并修复了您的loadData
功能:
$scope.loadData = function (entype, type) {
var value = 0;
if ($scope.Testing !== undefined) {
for (var i = 0; i < $scope.Testing.length; i++) {
var item = $scope.Testing[i];
if (item.TestingTypeId === type.Id && item.EnvironmentTypeId === entype.Id) {
value = item.value;
break;
}
}
}
return value;
};
forEach
内的那个else
也是错误的,因为如果第一项匹配,第二项将进入else
块并覆盖该值,这就是我删除该else
并使用break
的原因。
我认为代码可以改进,但这解决了您最初的问题。
这是你的弹簧固定的。
您需要执行以下操作
https://scotch.io/tutorials/building-dynamic-angular-forms-with-ngrepeat-and-ngform
<form name="userForm" novalidate>
<div class="form-group" ng-repeat="user in formData.users">
<label>{{ user.name }}'s Email</label>
<input type="text" class="form-control" name="email" ng-model="user.email" required>
<p class="help-block" ng-show="userForm.email.$invalid">Valid Email Address Required</p>
</div>
</form>
注意ng-repeat
的使用方式