我正在尝试在比率(用户输入)方面增加bar的百分比。一旦用户提交了他的输入,该值就应该通过该输入来增加。我如何使用ng风格来实现这一点。
var tech = [
{name: "android", rate: 0, bar: 10},
{name: "angular", rate: 0, bar: 10},
{name: "node", rate: 0, bar: 10},
{name: "maven", rate: 0, bar: 10},
{name: "log", rate:0, bar: 10},
{name: "vs2019", rate: 0, bar: 10}
];
$scope.tech = tech;
$scope.incrementRate= function(t,r)
{
t.rate = r;
t.bar = parseInt(t.bar) + Number(r); //giving NaN
alert(t.bar); //giving undefined
};<table>
<tr>
<td>Select course:</td>
<td>
<select class="form-control contact-text" name="course" ng-model="tech.name">
<option ng-repeat="t in tech" ng-value="t.name">{{t.name}}</option>
</select>
<br>
</td>
</tr>
<tr>
<td>Rate:</td>
<td>
<input type="radio" class="ml-3" name="rate" value="1" checked ng-model="tech.rate"> 1
<input type="radio" class="ml-3" name="rate" value="2" ng-model="tech.rate"> 2
<input type="radio" class="ml-3" name="rate" value="3" ng-model="tech.rate"> 3
<input type="radio" class="ml-3" name="rate" value="4" ng-model="tech.rate"> 4
<input type="radio" class="ml-3" name="rate" value="5" ng-model="tech.rate"> 5
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<br>
<br>
<button type="submit"
name="rate" class="btn btn-primary"
ng-click="incrementRate(tech,tech.rate)">Rate</button>
</td>
</tr>
</table>
<!-- for eg, -->
Android:
<div class="wrapper">
<div class="android skills" ng-style="{'width':tech[0].bar+'%'}">
{{tech[0].bar+'%'}}
</div>
</div>发布于 2019-04-29 21:24:25
t.bar是undefined,因为在您调用incrementRate(tech,tech.rate)的地方,tech是$scope.tech -所有技术的列表。不是您在ng-repeat中使用的t。
基本上,您混合了tech作为技术列表和tech作为选择的技术。我建议您使用$scope.techList作为列表,使用$scope.tech作为选择的技术。
使用ng-model="tech"和ngOptions使select能够选择技术。
发布于 2019-04-29 23:08:41
将$scope.tech定义为数组:
$scope.tech = [
{...}
];但是在您的视图中,您正在尝试访问它,就好像它是一个具有不存在的rate属性的对象:
<button type="submit"
ng-click="incrementRate(tech,tech.rate)">Rate</button>
<!-- tech is an array, and has no property called `rate`-->如果您在此处放置一些日志消息,您将看到以下错误:
$scope.incrementRate= function(t,r)
{
console.log(t) // Array(6)
console.log(r) // Undefined!
...
};此外,将select组件的模型指定为数组的属性也不是一个好的选择。这非常令人困惑。使用专用变量来分配选定的项。您还通过使用带有选项的ngRepeat而不是ngOptions,使事情变得非常困难。使用这种方法,您只能访问item的字符串表示,而不能访问item对象本身。
<select ng-model="selectedTech" ng-options="t as t.name for t in tech track by t.name">
</select>现在,您可以在函数中引用所选项目:
<button type="submit"
ng-click="incrementRate(selectedTech)">Rate</button>$scope.incrementRate= function(techItem)
{
console.log(techItem) // {name: "angular", rate: 0, bar: 10},
console.log(techItem.rate) // 0
...
};由于selectedTech是$scope的属性,您甚至不需要将其作为变量传递:
<button type="submit"
ng-click="incrementRate()">Rate</button>$scope.incrementRate= function()
{
console.log($scope.selectedTech) // {name: "angular", rate: 0, bar: 10},
console.log($scope.selectedTech.rate) // 0
...
};https://stackoverflow.com/questions/55904245
复制相似问题