我正在做一个应用程序,当你点击input
时会出现一个虚拟键盘。减量应该减去ng-model food.Pezzi
,并且它可以正常工作。但增量不起作用:它增加了一个' 1。为什么? PLUNKER CODE
(奇怪的是你按下递减按下递增,增量工作....)
标记
<td>
<a data-role="button" data-theme="e" ng-click="food.Pezzi = food.Pezzi-1; "
style="background-color: rgba(246, 246, 246, 0.2); border-color: rgba(0, 0, 0, 0.27); text-shadow: 0px 1px 0px #F3F3F3;color: #333;">
Decrement
</a>
</td>
<td>
<a data-role="button" data-theme="b" class="zero" ng-click='food.Pezzi=food.Pezzi.toString()+"0"'>
0
</a>
</td>
<td>
<a data-role="button" data-theme="e" class="pos" ng-click='food.Pezzi = food.Pezzi + 1'
style="background-color: rgba(246, 246, 246, 0.2); border-color: rgba(0, 0, 0, 0.27); text-shadow: 0px 1px 0px #F3F3F3;color: #333;">
Increment
</a>
</td>
谢谢你的建议
答案 0 :(得分:2)
将您的代码更改为var itemToClone = { "Selection": "", "Pezzi": 0 };
而不是var itemToClone = { "Selection": "", "Pezzi": "" };
。您正在使用空字符串进行初始化,并附加到字符串而不是添加数字。
其他地方也一样。在修改输入后,必须使用parseInt
键入强制转换字符串。
<强>更新强>
那是我们的。让我们在您的控制器中添加一个方法,如下所示:
$scope.inc = function(food) {
food.Pezzi = food.Pezzi || "0"
food.Pezzi = parseInt(food.Pezzi.toString()) + 1;
};
现在,修改您的增量按钮ng-click
,使其符合下列条件:ng-click="inc(food)"
答案 1 :(得分:2)
首先,您以不好的方式使用AngularJS,从不将Business Logic放在您的视图中。
顺便说一句,您的错误取决于属性 Pezzi 的类型,对于数学操作,您需要使用数字,但是,在javascript中, + 运算符甚至用于字符串连接...看看以下两个例子:(第一个是正确的,第二个,因为丢失了类型,另外执行字符串连接而不是和)
angular
.module('test', [])
.controller('TestCtrl', function($scope) {
var vm = $scope;
vm.food = { pezzi: 0 };
vm.increment = function() { vm.food.pezzi += 1; };
vm.decrement = function() { if(vm.food.pezzi > 0) vm.food.pezzi -= 1; };
vm.reset = function() { vm.food.pezzi = 0; };
vm.getType = function() {
return typeof vm.food.pezzi;
}
vm.foodCloned = { pezzi: 0 + '' };
vm.incrementCloned = function() { vm.foodCloned.pezzi += 1 + ''; };
vm.decrementCloned = function() { vm.foodCloned.pezzi -= 1 + ''; };
vm.resetCloned = function() { vm.foodCloned.pezzi = 0 + ''; };
vm.getClonedType = function() {
return typeof vm.foodCloned.pezzi;
}
})
;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="test">
<div ng-controller="TestCtrl">
<button ng-click="decrement($event)">Decrement</button>
<button ng-click="increment($event)">Increment</button>
<button ng-click="reset($event)">Reset</button>
<h1 ng-bind="food | json"></h1>
<div ng-bind="getType()"></div>
<hr><hr>
<button ng-click="decrementCloned($event)">Decrement</button>
<button ng-click="incrementCloned($event)">Increment</button>
<button ng-click="resetCloned($event)">Reset</button>
<h1 ng-bind="foodCloned | json"></h1>
<div ng-bind="getClonedType()"></div>
</div>
</article>
&#13;