angular: Validate multiple dependent fields

前端 未结 5 1277
予麋鹿
予麋鹿 2021-02-02 09:06

Let\'s say I have the following (very simple) data structure:

$scope.accounts = [{
   percent: 30,
   name: \"Checking\"},
 { percent: 70,
   name: \"Savings\"}]         


        
5条回答
  •  无人及你
    2021-02-02 09:35

    Ok, the following works (again, "share" is "percent"):

    app.directive('shareValidate', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attr, ctrl) {
            scope.$watch(attr.shareValidate, function(newArr, oldArr) {
                var sum = 0;
                angular.forEach(newArr, function(entity, i) {
                    sum += entity.share;
                });
                if (sum === 100) {
                    ctrl.$setValidity('share', true);
                    scope.path.offers.invalidShares = false;
                }
                else {
                    ctrl.$setValidity('share', false);
                    scope.path.offers.invalidShares = true;
                }
            }, true); //enable deep dirty checking
        }
    };
    });
    

    In the HTML, set the attribute as "share-validate", and the value to the set of objects you want to watch.

提交回复
热议问题