在控制器中调用验证指令功能

时间:2017-06-13 20:45:34

标签: angularjs angularjs-directive angular-controller

我试图从控制器中的指令调用验证函数。有可能吗?

我的指示是这样的:

app.directive('evenNumber', function(){
  return{
    require:'ngModel',
    link: function(scope, elem, attrs, ctrl){
      ctrl.$parsers.unshift(checkForEven);
      function checkForEven(viewValue){
        if (parseInt(viewValue)%2 === 0) {
          ctrl.$setValidity('evenNumber',true);
        }
        else{
          ctrl.$setValidity('evenNumber', false);
        }
        return viewValue;
      }
    }
  };
});

我想从控制器调用函数checkForEven。

$scope.copyFileContentToEditor = function(){
  $scope.code = $scope.content;
  // TODO call the checkForEven directive function to validate the $scope.code
}

有可能吗?有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可能需要在控制器和指令之间定义一个链接,以便彼此了解。

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World'; // this is just used for your directive model, it is not the part of the answer

  $scope.vm = {} // define this to create a shared variable to link the controller and directive together.
});

app.directive('evenNumber', function(){
return{
require:'ngModel',
scope: {'vm': '='},
restrict: 'A',
link: function(scope, elem, attrs, ctrl){

  function checkForEven(){
    alert('I get called.')
  }

  scope.vm.checkForEven = checkForEven; // once the directive's method is assigned back to "vm", so you could trigger this function from your controller by call this vm.checkForEven;



}}})

HTML

<div ng-model="name" even-number vm="vm"></div>

Plunker Example

答案 1 :(得分:1)

将该函数添加为ngModel控制器的属性:

app.directive('evenNumber', function(){
  return{
    require:'ngModel',
    link: function(scope, elem, attrs, ctrl){
      ctrl.$parsers.unshift(checkForEven);
      //ADD checkForEven to ngModel controller
      ctrl.checkForEven = checkForEven;          

      function checkForEven(viewValue){
        if (parseInt(viewValue)%2 === 0) {
          ctrl.$setValidity('evenNumber',true);
        }
        else{
          ctrl.$setValidity('evenNumber', false);
        }
        return viewValue;
      }
    }
  };
});

然后命名表单和输入元素:

<form name="form1">
    <input name="input1" ng-model="vm.input1" even-number />
</form>

然后,控制器可以在它附加到范围的位置引用它:

$scope.copyFileContentToEditor = function(){
    $scope.code = $scope.content;

    //CALL the function
    $scope.form1.input1.checkForEven($scope.vm.input1);

}
相关问题