How can I call a directive function from outside?

两盒软妹~` 提交于 2019-12-11 22:13:58

问题


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;
            };                
        }
    }
    });

回答1:


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



来源:https://stackoverflow.com/questions/25855811/how-can-i-call-a-directive-function-from-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!