【问题标题】:Call validation directive function in the controller在控制器中调用验证指令函数
【发布时间】:2017-06-13 20:45:33
【问题描述】:

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

我的指令是这样的:

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
}

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

【问题讨论】:

  • 来自 evenNumber 指令控制器?
  • 我想在$scope.copyFileContentToEditor函数中调用'evenNumber'指令的checkForEven函数

标签: angularjs angularjs-directive angular-controller


【解决方案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

【讨论】:

    【解决方案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);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多