Andre Evangelista Andre Evangelista - 3 months ago 8
AngularJS Question

How can I call a directive function from outside?

I have a directive that generates a list for me. This directive has methods for pagination. I would like to control this list using keyboard so that when I press left or right the list pages next or previous.

Is there anyway I could do that?

bellow there is my directive code:

app.directive("gridview", function(){
return {
restrict:'E',
transclude: true,
template:'<div><button ng-disabled="!hasPrevious()" ng-click="onPrev()"> Previous </button><button ng-disabled="!hasNext()" ng-click="onNext()"> Next </button></div><div ng-transclude></div>',
scope:{
'currentItem':'=',
'currentPage':'=',
'pageLimit':'=',
'data':'=',
'totalPages' :'&'
},
link:function($scope, element, attrs){

$scope.size = function(){
return angular.isDefined($scope.data) ? $scope.data.length : 0;
};

$scope.end = function(){
return $scope.start() + $scope.pageLimit;
};

$scope.start = function(){
return $scope.currentPage * $scope.pageLimit;
};

$scope.totalPages = function(){
$scope.totalPages({theTotal : $scope.size});
};

$scope.page = function(){
return !!$scope.size() ? ( $scope.currentPage + 1 ) : 0;
};

$scope.hasNext = function(){
return $scope.page() < ( $scope.size() / $scope.pageLimit ) ;
};

$scope.onNext = function(){
$scope.currentPage = parseInt($scope.currentPage) + 1;
$scope.currentItem = parseInt($scope.currentPage) + 1;
};

$scope.hasPrevious = function(){
return !!$scope.currentPage;
} ;

$scope.onPrev = function(){
$scope.currentPage=$scope.currentPage-1;
};
}
}
});

Answer

You can always use the Angular event system, which will allow you to interact between your controller and directive.

Simply broadcast an event in your controller and listen to it in your directive to call the function you want.

Controller

$scope.$broadcast('onPrev')

Directive

$scope.$on('onPrev', function () {
  $scope.onPrev()
})

that's for the main question, but your more specific problem, you should have a look to ngKeypress