如何从一个指令传达到另一个指令指令、传达

2023-09-13 04:28:43 作者:猪仙

我有拖指令一个是NG-网格中的另一个是分页,当我在一个指令NG-电网指令点击页码应根据所改变,我可以对任何想法。

I have tow directives one is for ng-grid another is for pagination when I click page numbers in one directive ng-grid directive should be changed according to that, can I have any idea on that.

推荐答案

有很多方法来实现它:例如:

There are many ways to achieve it: For example:

一解

您可以共享数据:

<directive-one attribute="value" other-attribute="value2" shared-variable="yourData">
<directive-two shared-variable="yourData">

和设置 $观看该值指示首先在

scope.$watch('yourData',function(newVal,oldVal){ //your logic called after change });

第二类解决方案

您可以使用事件:

app.directive('first',function(){
    return{
        restrict: 'E',
        template: 'Im first directive!',
        scope: true,
        link:function(scope,elem,attrs){
            scope.$on('event',function(event,args){
               alert(args); 
            });
        }
    }    
});

app.directive('second',function($rootScope){
    return{
        restrict: 'E',
        template: 'Im second directive! <button ng-click="click()">click me!</button>',
        scope: true,
        link:function(scope,elem,attrs){
            scope.click = function(){
                $rootScope.$broadcast('event','hello!');    
            };

        }
    }    
});

事件是由 $ rootScope发送广播$('事件','你好!'); 。这意味着事件是由根向下范围发送到子作用域。 http://jsfiddle.net/aartek/fJs69/

Event is sent by $rootScope.$broadcast('event','hello!');. It means event is sent by your root scope downwards to child scopes. http://jsfiddle.net/aartek/fJs69/