加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 你能从一个模块中的Controller向另一个模块中的指

发布时间:2020-12-17 17:48:04 所属栏目:安全 来源:网络整理
导读:我在一个单独的模块“app”和“directiveModule”中分别有一个控制器“MyController”和一个指令“MyDirective”. DirectiveModule已被注入“app”的angular.module中. 我遇到的问题是作为“app”的一部分,我有一个控制器发出一个事件“TEST”,指令的控制器
我在一个单独的模块“app”和“directiveModule”中分别有一个控制器“MyController”和一个指令“MyDirective”. DirectiveModule已被注入“app”的angular.module中.

我遇到的问题是作为“app”的一部分,我有一个控制器发出一个事件“TEST”,指令的控制器没有接收.如何成功获取自己模块的指令来捕获发射?这可能吗? (注意:我最初尝试过$scope,然后使用$rootScope,但两者都没有区别.)

我的控制器:

app.controller('MyController',function($scope,$rootScope) {
  $rootScope.$emit('TEST');
});

我的指示:

directiveModule.directive('MyDirective',['$rootScope','MyService',function($rootScope,MyService) {

return {
   restrict: 'E',controller: ['$scope','$rootScope',$rootScope) {
        $rootScope.$on('TEST',function() {alert("Event Caught")})

}]};
}];

更新:看起来我的指令尚未在广播事件发布时启动.是否有办法让我可以“等待指令实例化”而不是等待“1000”ms的仲裁或其他替代方案?

解决方法

我认为你的指令需要捕获该事件的唯一情况是根据MyController获取一些初始数据,因为如果你的指令独立于MyController,你不需要捕获该事件,只需单独启动指令即可.

我的解决方案是使用$watch在MyController的初始数据准备就绪时收到通知.

app.controller('MyController',function($scope) {
   $scope.data = {}; //initialize the data,this data could be fetched from an ajax
});

directiveModule.directive('MyDirective',['MyService',function(MyService) {

return {
   restrict: 'E',function($scope) {
        $scope.$watch("data",function(newValue,OldValue,scope){
             //do your work here when data is changed.
        });  
    }]};
}];

如果您在指令中使用隔离范围:

directiveModule.directive('MyDirective',function(MyService) {

    return {
       restrict: 'E',scope : {
           directiveData:"=",},function($scope) {
            $scope.$watch("directiveData",scope){//watch on the directive scope property
                 //do your work here when data is changed.
            });  
        }]};
    }];

你的HTML可能如下所示:

<my-directive directive-data="data" /> //bind isolate scope directive property with controller's scope property.

我认为以下问题是类似的情况:

> AngularJS : Directive not able to access isolate scope objects
> AngularJS : directives and scope

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读