您好我想制作验证指令。它基本上会在服务器上调用远程验证。我希望这样的事情:
<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作为函数的名称。但我不能在传递我的参数的控制器范围上执行它;
非常感谢任何帮助!
答案 0 :(得分: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
}
}
})