在控制器中调用验证指令函数



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

我的指令是这样的:

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
}

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

您可能需要在控制器和指令之间定义一个链接,以使它们相互了解。

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>

普伦克示例

将函数添加为 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);
}

最新更新