问题
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">
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
})
}
}
})
But I can't figure out how to call the clientController from inside the directive.
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;
Any help would be much appreciated!
回答1:
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
}
}
})
来源:https://stackoverflow.com/questions/16598337/how-to-call-an-application-controller-method-from-angular-js-directive