0

嗨,我想做一个验证指令。它基本上会在服务器上调用远程验证。我会期待这样的事情:

<input type="text" id="nome" required ng-model="client.context" available="checkAvailableContexts">

这应该在我的 ClientController 上调用一个方法,如下所示:

$scope.checkAvailableContexts = function(contexto, callbacks) {
    service.checkContextAvailability(contexto, callbacks);
}

这是我的服务方法:

this.checkContextAvailability = function(context, externalCallbacks) {
 var url = angular.url("/clients/context/" + context + "/available"),
     callback = {
         success: function(){},
         error: function(){}
     };

 $.extend(callback, externalCallbacks)
 $.ajax({
     url: url,
     data: { context: context },
     success: function(data){
         $timeout(function(){
             callback.success(data); 
         },100);
     },
     type: "GET",
     dataType: "json",
     contentType: "application/json;charset=UTF-8onte"   
 });
};

我的指令是这样的:

.directive('available', function(){
  return {
      restrict: "A",
      require: "ngModel",
      replace: true,
      link: function(scope, element, attrs, controller){
          controller.$parsers.unshift(function (viewValue) {
                          //call the ClientsController method passing viewValue
                          //and callbacks that update the validity of the context
          })
      }
  }
})

但我不知道如何从指令内部调用 clientController。

我知道我有 attrs.available 作为函数的名称。但是我无法在传递参数的控制器范围内执行它;

任何帮助将非常感激!

4

1 回答 1

1

你不需要调用控件,你只需要和它共享变量。

您可以做的是与指令共享一个对象,例如:

<input type="text" id="nome" 
 required ng-model="client.context" 
 available="availableOpts">

在您的范围内,您添加一个具有共享变量的变量,例如:

$scope.availableOpts = {
   check: checkAvailableContexts,
   context: ...;
   callbacks: ...;
}

在你的指令中,你在范围内得到它:

.directive('available', function(){
return {
  restrict: "A",
  require: "ngModel",
  replace: true,
  scope: {available: "="}
  link: function(scope, element, attrs, controller){

  // At this point, you have an variable at directive scope, that is shared
  // with the controller, so you can do:
  scope.available.check(scope.availabe.context, scope.available.callbacks);
  // the controler will have now a var $scope.availableOpts.result
  // with the return of the function tha you call

  }
 }
})
于 2013-05-16T22:40:19.500 回答