1
我是Angularjs的新手,並且在實現客戶端驗證時遇到困難。由於這個post我能夠限制用戶輸入,但是現在我需要將每列的總和限制爲24.目前我能夠對列進行求和,但是我很難與其交互,設置它的值如果新數量超過24,則返回舊值。下面是使用當前代碼的fiddle。Angularjs,限制列總和爲x
var app = angular.module('myapp', []);
app.controller('Ctrl', function($scope) {
$scope.Rows = [{
FriHrs: 0,
SatHrs: 0,
SunHrs: 0,
MonHrs: 0,
TueHrs: 0,
WedHrs: 0,
ThuHrs: 0
}];
$scope.AddRow = function() {
$scope.Rows.push({
FriHrs: 0,
SatHrs: 0,
SunHrs: 0,
MonHrs: 0,
TueHrs: 0,
WedHrs: 0,
ThuHrs: 0
})
};
});
app.filter('sumByKey', function() {
return function(data, key) {
if (typeof(data) === 'undefined' || typeof(key) === 'undefined') {
return 0;
}
var sum = 0.0;
for (var i = data.length - 1; i >= 0; i--) {
sum += parseFloat(data[i][key]);
}
return sum;
};
});
app.directive('numberOnlyInput', function() {
return {
restrict: 'EA',
template: '<input style="width:30px" ng-model="inputValue"/>',
scope: {
inputValue: '=',
},
link: function(scope) {
scope.$watch('inputValue', function(newValue, oldValue) {
var arr = String(newValue).split("");
var arr2 = String(newValue).split(".");
if (arr.length === 0) return;
if (arr.length === 1 && arr[0] === '.') return;
if (arr.length === 2 && newValue === '.') return;
if (arr2.length === 2) {
if (arr2[1].length === 3) {
scope.inputValue = oldValue;
}
}
if (isNaN(newValue)) {
scope.inputValue = oldValue;
}
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<table ng-app="myapp" ng-controller="Ctrl" class="table">
<thead>
<tr>
<th>Sat<br/><span id="totalSat"></span><small>{{Rows|sumByKey:'SatHrs'}}</small></th>
<th>Sun<br/><span id="totalSun"></span><small>{{Rows|sumByKey:'SunHrs'}}</small></th>
<th>Mon<br/><span id="totalMon"></span><small>{{Rows|sumByKey:'MonHrs'}}</small></th>
<th>Tue<br/><span id="totalTue"></span><small>{{Rows|sumByKey:'TueHrs'}}</small></th>
<th>Wed<br/><span id="totalWed"></span><small>{{Rows|sumByKey:'WedHrs'}}</small></th>
<th>Thu<br/><span id="totalThu"></span><small>{{Rows|sumByKey:'ThuHrs'}}</small></th>
<th>Fri<br/><span id="totalFri"></span><small>{{Rows|sumByKey:'FriHrs'}}</small></th>
</tr>
</thead>
<tbody id="detailTable">
<tr ng-repeat="Row in Rows">
<td><number-only-input input-value="Row.SatHrs"/></td>
<td><number-only-input input-value="Row.SunHrs"/></td>
<td><number-only-input input-value="Row.MonHrs"/></td>
<td><number-only-input input-value="Row.TueHrs"/></td>
<td><number-only-input input-value="Row.WedHrs"/></td>
<td><number-only-input input-value="Row.ThuHrs"/></td>
<td><number-only-input input-value="Row.FriHrs"/></td>
</tr>
<tr>
<td colspan="7"><input type="button" value="Add Record" ng-click="AddRow()"/></td>
</tr>
</tbody>
</table>
重讀我的問題,我看到我misphrased它。該列的總和不應超過24,但不應該難以從行轉換爲列。謝謝! – Alex
對不起,編輯添加列...接受? :) – malix