angular: Validate multiple dependent fields

前端 未结 5 1259
予麋鹿
予麋鹿 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:31

    You can define a single directive that is only responsible for this check.

    And here's the simple directive's code.

    app.directive('sumUpToHundred', function() {
      return {
        scope: {
          accounts: '<'
        },
        require: {
          formCtrl: '^form'
        },
        bindToController: true,
        controllerAs: '$ctrl',
        controller: function() {
          var vm = this;
    
          vm.$doCheck = function(changes) {
            var sum = vm.accounts.map((a)=> a.percent).reduce((total, n)=> total + n);
            if (sum !== 100) {
              vm.formCtrl.$setValidity('sumuptohundred', false);
            } else {
              vm.formCtrl.$setValidity('sumuptohundred', true);
            }
          };
        }
      };
    });
    

    Here's a plunker.

提交回复
热议问题