Вызвать функцию директивы проверки в контроллере

Я пытаюсь вызвать функцию проверки из директивы в контроллере. Является ли это возможным?

Моя директива примерно такая:

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 ответа

Добавьте функцию в качестве свойства контроллера 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);

}

Возможно, вам потребуется определить связь между вашим контроллером и вашей директивой, чтобы они узнали друг друга.

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>

Пример плунжера

Другие вопросы по тегам