从控制器调用角度指令

时间:2016-01-04 10:43:38

标签: angularjs

我有一个mobi滚动日期选择器,我已经使用指令完成了年龄验证。 我正在为注册过程进行多步骤表单验证。如果我点击后退按钮,我该如何再次调用该指令(即年龄验证)。

<input type="text" id="dateOfBirth" placeholder="Please Select ..."  data-ng-model="personalDetailsObj.personalDetails.dob" name="dob" ng-required="true" age-valid mobi-date=true /> 

指令

.directive('ageValid', ['$filter', function($filter) {
  return {
    restrict: 'A',
    require: 'ngModel',        
    link: function(scope, element, attrs, ngModel) {
      ngModel.$validators.validAge = function(modelValue, viewValue) {
        var todayDate = new Date(),
          todayYear = todayDate.getFullYear(),
          todayMonth = todayDate.getMonth(),
          todayDay = todayDate.getDate(),
          dateFieldVal = viewValue,
          birthYear = viewValue.split('/')[2],
          birthMonth = viewValue.split('/')[1],
          birthDay = viewValue.split('/')[0],
          age = todayYear - parseInt(birthYear);

          if(todayMonth < parseInt(birthMonth) - 1){
            age--;
          }
          if(parseInt(birthMonth) - 1 === todayMonth && todayDay < parseInt(birthDay)){
            age--;
          }                  
          return age >= 21;
      };
    } 
  }
}])

控制器

$scope.backbutton = function(){

};

2 个答案:

答案 0 :(得分:3)

你应该使用工厂作为中间人:

<强>指令:

.directive('ageValid', ['$filter','Age', function($filter,Age) {
  return {
    restrict: 'A',
    require: 'ngModel',        
    link: function(scope, element, attrs, ngModel) {
      ngModel.$validators.validAge = function(modelValue, viewValue) {
       return Age.ageValidation(modelValue, viewValue);
      };
    } 
  }
}])

<强>控制器:

$scope.backbutton = function(){

};

<强>工厂:

.factory("Age", function (NombresGuardado) {

    return {
        ageValidation: function (modelValue, viewValue) {
             var todayDate = new Date(),
              todayYear = todayDate.getFullYear(),
              todayMonth = todayDate.getMonth(),
              todayDay = todayDate.getDate(),
              dateFieldVal = viewValue,
              birthYear = viewValue.split('/')[2],
              birthMonth = viewValue.split('/')[1],
              birthDay = viewValue.split('/')[0],
              age = todayYear - parseInt(birthYear);

              if(todayMonth < parseInt(birthMonth) - 1){
                age--;
              }
              if(parseInt(birthMonth) - 1 === todayMonth && todayDay < parseInt(birthDay)){
                age--;
              }                  
              return age >= 21;
        }
    }

答案 1 :(得分:0)

您可以从指令扩展控制器范围。在您的情况下,您使用指令中的相同作用域(未指定scope属性),因此您的代码可能看起来像=&gt;

// Directive

.directive('ageValid', ['$filter', function($filter) {
  return {
    restrict: 'A',
    require: 'ngModel',        
    link: function(scope, element, attrs, ngModel) {
      scope.doSomething = function() {
        console.log("hello");
      }
    } 
  }
}])

// Controller

$scope.backbutton = function(){
  $scope.doSomething();
};