angular: Validate multiple dependent fields

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

    For my sanity

    HTML

    JS

    'use strict';
    
    angular.module('myModule')
      .controller('DaysCtrl', function($scope, $timeout) {
        $scope.initDate = new Date();
        $scope.startDate = angular.copy($scope.initDate);
        $scope.endDate = angular.copy($scope.startDate);
        $scope.endDate.setTime($scope.endDate.getTime() + 6*24*60*60*1000);
    
        $scope.$watch("daysForm", function(){
          //fields are only populated after controller is initialized
          $timeout(function(){
            //not all viewalues are set yet for somereason, timeout needed
            $scope.daysForm.startDate.$validators.checkAgainst = function(){
              $scope.daysForm.startDate.$setDirty();
              return (new Date($scope.daysForm.startDate.$viewValue)).getTime() <=
                (new Date($scope.daysForm.endDate.$viewValue)).getTime();
            };
    
            $scope.daysForm.endDate.$validators.checkAgainst = function(){
              $scope.daysForm.endDate.$setDirty();
              return (new Date($scope.daysForm.startDate.$viewValue)).getTime() <=
                (new Date($scope.daysForm.endDate.$viewValue)).getTime();
            };
          });
        });
    
        $scope.runAllValidators = function(){
          //need to run all validators on change
          $scope.daysForm.startDate.$validate();
          $scope.daysForm.endDate.$validate();
        };
    
        $scope.applyDefaultDays = function(){
            //do stuff
        }
      });
    

提交回复
热议问题