2013-05-16 58 views
0

您好我想制作一个验证指令。它基本上会调用服务器上的远程验证。我希望这样的事情:如何从角度js指令调用应用程序控制器方法

<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作为函数的名称。但是我无法在传递参数的控制器范围上执行它;

任何帮助将不胜感激!

回答

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 

    } 
} 
})