我需要计算用户输入的对象属性的总和。我有一个带手表的功能设置,但我没有得到结果。我有一个小提琴,我有。 working fiddle
$scope.model = {}
function total() {
var totalNumber = 0;
totalNumber = totalNumber + $scope.model.minPrice + $scope.model.maxPrice + $scope.model.occup
return totalNumber;
};
$scope.$watch('model', function (newVal, oldVal) {
$scope.model.total = total();
console.log($scope.model.total)
}, true);
和控制台的截图
答案 0 :(得分:3)
重载+
运算符以连接字符串。
一种选择是在添加之前使用parseInt()
将字符串转换为整数。您也可以使用逻辑OR运算符来处理NaN
。这只是一种方式。
totalNumber = (parseInt($scope.model.minPrice) || 0)
+ (parseInt($scope.model.maxPrice) || 0)
+ (parseInt($scope.model.occup) || 0);
console.log($scope.model);
答案 1 :(得分:1)
这可能很简单,但您需要过滤空值和无效值。
$scope.$watch('model', function() {
$scope.model.total = parseInt($scope.model.minPrice)
+ parseInt($scope.model.maxPrice)
+ parseInt($scope.model.occup);
}, true);
<强> Demo 强>