如何从角JS指令调用应用程序控制器的方法 [英] How to call an application controller method from angular js directive
问题描述
您好我想打一个确认指令。它基本上将调用服务器上的远程验证。我希望是这样的:
Hi I want to make a validation directive. It basically will call a remote validation on the server. I would expect something like this:
<input type="text" id="nome" required ng-model="client.context" available="checkAvailableContexts">
和应该调用方法对我ClientController是这样的:
and that should call a method on my ClientController like this:
$scope.checkAvailableContexts = function(contexto, callbacks) {
service.checkContextAvailability(contexto, callbacks);
}
这是我服务的方法:
and this is my service method:
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"
});
};
我的指令是这样的:
my directive is something like this:
.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。
But I can't figure out how to call the clientController from inside the directive.
我知道我有attrs.available作为函数的名称。但我不能执行它的控制器范围内通过我的参数;
I know I have attrs.available as the name of the function. But I can't execute it on the controller scope passing my parameters;
任何帮助将是非常美联社preciated!
Any help would be much appreciated!
推荐答案
您不需要调用控件,你只需要与它共享变量。
You don't need to call the control, you just need to share variables with it.
你可以做的是与指令共享一个对象,如:
What you can do is share an object with the directive, like:
<input type="text" id="nome"
required ng-model="client.context"
available="availableOpts">
在你的范围,你加一个变量,共享增值经销商,如:
At your scope, you add a variable with shared vars, like:
$scope.availableOpts = {
check: checkAvailableContexts,
context: ...;
callbacks: ...;
}
在你的指令,在你的范围得到它:
At you directive, you get it at the scope:
.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
}
}
})
这篇关于如何从角JS指令调用应用程序控制器的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!