如何从外部调用指令函数? [英] How can I call a directive function from outside?

查看:39
本文介绍了如何从外部调用指令函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令可以为我生成一个列表.该指令具有分页方法.我想使用键盘控制此列表,以便当我向左或向右按​​列表页面的下一页或上一页时.

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.

无论如何我能做到吗?

下面是我的指令代码:

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

推荐答案

您始终可以使用 Angular 事件系统,它允许您在控制器和指令之间进行交互.

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.

控制器

$scope.$broadcast('onPrev')

指令

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

这是主要问题,但你更具体的问题,你应该看看ngKeypress

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

这篇关于如何从外部调用指令函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆