如何解决嵌套指令作用域问题?

How can I resolve a nested Directive scope issue?

本文关键字:指令 作用域 问题 嵌套 何解决 解决      更新时间:2023-09-26

我使用ionic:我创建了一个"Notification"指令,它做了一些预处理,以确定根据属性传递的对象显示哪种类型的通知('警报','消息'或'重要消息')。在该指令的模板中,我调用了另一个名为"更新通知"的指令-这是一个项目选项,当用户将项目向左滑动时显示,并且(应该)调用带有表单的更新模式,该表单的模型通过属性"通知"传递。"

我遇到的问题是"更新通知"的模板正在调用showUpdateNotification(),但它似乎正在调用"通知"指令的作用域函数;尽管"Update Notification"指令有一个定义的作用域。

我想在"更新通知"指令中定义更新功能,以便能够使用另一个模板在应用程序的其他地方调用它,但我不确定如何解决我的作用域问题。

谢谢你的帮助!

通知指令:

.directive("notification", function($rootScope, BibleService, FirebaseLoginService){
    return{
        restrict: 'AE',
        scope:{
            type: '@?type',
            message: '=?message'
        },
        replace: true,
        template: "<div ng-include='contentUrl'></div>",
        link: function(scope, element, attrs){
            scope.contentUrl = 'templates/directives/' + attrs.file + '.html';
               attrs.$observe("file",function(v){
                   scope.contentUrl = 'templates/directives/' + v + '.html';
               });
        },
        controller: function($scope, $rootScope){
            //something interesting here.
            $scope.hidden = false;
            $scope.leaderImage = "";
            $scope.notification = "";
            $scope.canEdit = false;
            if($scope.message){
                $scope.leaderImage = $scope.message.leader.image;
                if($scope.message.important){
                    $scope.type ="important"
                }else{
                    $scope.type = "message"
                }
                if(FirebaseLoginService.loggedUser().id === $scope.message.leader.id){
                    $scope.canEdit = true;
                }else{
                    $scope.canEdit = false;
                };
            }


            if($scope.type === "alert" && $rootScope.pastDue){
                $scope.title = "ATTENTION:"
                $scope.notification = $rootScope.pastDueNotification;
            }else if($scope.type === "message"){
                if($scope.message){
                    $scope.title = $scope.message.title;
                    $scope.notification = $scope.message.text;
                }
            }else{
                if($scope.message){
                    $scope.title = $scope.message.title;
                    $scope.notification = $scope.message.text;
                }
            }
            $scope.closeNotification = function(){
                $scope.hidden = true;
            }           
        }
    };
});
通知模板:

<ion-list show-delete="false" can-swipe="true">  
<ion-item ng-if="type === 'alert'" ng-hide="hidden" class="item item-icon-left notification-alert item-text-wrap" ng-href="#/app/billing">
<i class="icon ion-alert-circled light"></i>
<h2 class="light"><b>{{title}}</b></h2><hr>
<p><span class="light"><b>{{notification}}</b></span></p>
<ion-option-button class="button-calm" ng-click="closeNotification()">
  Close
</ion-option-button>
</ion-item>
<ion-item ng-if="type === 'important'" ng-hide="hidden" class="item item-icon-left notification-important item-text-wrap">
<i class="icon ion-android-hand royal"></i>
<div class="row">
    <div class="col-80">
        <h2 class="light"><b>Important Message: </b></h2>
        <hr><p ng-if="title"><span class="royal"><b>{{title}}</b></span></p>
        <p class="small"><span class="light"><b>{{notification}}</b></span></p> 
        {{message}}
    </div>
    <div class="col-20">
        <img class="notification-thumb" ng-src="{{leaderImage}}" alt="">
    </div>
</div>
<update-notification notification="message" file="updateNotificationOption"></update-notification>
<ion-option-button class="button-calm" ng-click="closeNotification()">
  Close
</ion-option-button>
</ion-item>
<ion-item ng-if="type === 'message'" ng-hide="hidden" class="item item-icon-left notification-message item-text-wrap">
<i class="icon ion-paper-airplane dark"></i>
<div class="row">
    <div class="col-80">
        <h2>Message:</h2>
        <hr><p ng-if="title"><b>{{title}}</b></p>
        <p class="small">{{notification}}</p>
        {{message}}
    </div>
    <div class="col-20">
        <img class="notification-thumb" ng-src="{{leaderImage}}" alt="">
    </div>
</div>
<update-notification notification="message" file="updateNotificationOption"></update-notification>
<ion-option-button class="button-calm" ng-click="closeNotification()">
  Close
</ion-option-button>
</ion-item>

更新通知指令:

.directive("updateNotification", function($rootScope, $localStorage, $timeout, $ionicListDelegate, ChurchService){
    return{
        restrict: 'E',
        scope:{
            notification: '='
        },
        replace: true,
        template: "<div ng-include='contentUrl'></div>",
        link: function(scope, element, attrs){
            scope.contentUrl = 'templates/directives/' + attrs.file + '.html';
               attrs.$observe("file",function(v){
                   scope.contentUrl = 'templates/directives/' + v + '.html';
               });
        },
        controller: function($scope, $ionicModal, $location){
            var ctrl = this;
            $scope.notice = $scope.notification;
            var church = {};
            ChurchService.getbyLeader($localStorage.seedUser.leadershipID).then(function(ch){
                church = ch;
            });
            $scope.updateNotification = function (data) {
                $rootScope.show('Updating notification...');
                if(church.notifications){
                    for (var i=0; i<church.notifications.length; i++){
                        var note = church.notifications[i];
                        if(note.date === data.date){
                            note = data;
                        }
                    }
                }
                ChurchService.update(church).then(function(){
                    $scope.closeUpdateNotification();
                    $location.path('/app/church/'+data.id);
                    $rootScope.hide();
                }, ctrl.updateNotificationFailure);
            };
            ctrl.updateNotificationFailure = function(error) {
                console.log('POST ERROR:', error);
                $rootScope.notify("The Notification wasn't updated. Please try again later.")
            };
            $ionicModal.fromTemplateUrl('templates/updateNotification.html',{
                scope: $scope
            }).then(function(modal){
                $scope.updateNotificationModal = modal;
            });
            // Open the update modal
            $scope.showUpdateNotification = function() {
                $scope.updateNotificationModal.show();
                $ionicListDelegate.closeOptionButtons();
                //console.log($scope.prayerObj);
            };
            // Triggered in the update modal to close it
            $scope.closeUpdateNotification = function() {
                $scope.updateNotificationModal.hide();
            };
        }
    };
});

更新通知模板:

<ion-option-button class="button-balanced" ng-click="showUpdateNotification()">
Edit
</ion-option-button>

这是一个普朗克(抱歉Sass没有翻译好-看起来很糟糕)

我不能真正找到我的方法围绕你的例子,所以不是提供一个特定于你的例子的答案,我将介绍大多数人实现指令对指令沟通的方式。

<标题> SCOPE-CALLBACK h1> 可能是最常用的从内部作用域到外部实体的通信方式。注意我说的是"外部实体"而不是"外部范围"。这是因为它并不局限于指令对指令的通信。在内部指令中,像这样建立一个回调:
directive = {
    scope: {
        onFoo: '&'
    },
    link: function($scope, elem, attrs){
        elem.bind('onClick', function(evt){ 
             //with no callback params
             $scope.onFoo()
             //with callback params
             $scope.onFoo({ $args:'foo' })
        }
    }
}

你在使用该指令的模板中声明它,其中doSomething是在你的控制器上定义的方法:

<my-directive on-foo="doSomething()"/>

或使用回调参数

<my-directive on-foo="doSomething($args)"/>

通过require进行真正的指令间通信

让指令彼此通信的更复杂的方法是在定义指令时使用require字段。当一个自定义指令require是一个ng模型作为输入时,你会一直看到这种用法。例子:

directive = {
    require: '^ngModel',
    link: function($scope, elem, attrs, ngModel){
        ngModel.parsers.push( function(){ ... })
    }
}

在上面的例子中,指令可以访问所需的ngModelController api。在你的情况下,你可以在外部指令上定义一个控制器,然后在内部指令中要求它:

outerDirective = {
    controllerAs: 'outer',
    controller: function(){ 
         function OuterDirectiveController(){ ... }
         OuterDirectiveController.prototype.doOuter = function(){ ... }
         return OuterDirectiveController
    },
    template: '<div><input><div>...</div><div inner-directive></inner-directive>'
 }

在本例中,为了简洁起见,我只是在外部指令的模板中声明了内部指令。

 innerDirective = {
      require: 'outerDirective',
      link: function($scope, elem, attrs, outerDirective){
           elem.bind('submit', function(){ outerDirective.doOuter()})
      }
 }

<标题>事件总线h1> 是跨许多不同技术和语言与MVC框架的各种组件进行通信的经典方式。它当然不是有棱角的做事方式,我通常不会推荐这种方法,除非你不能让任何其他工作。它还受范围层次结构的影响。最后,它的主要缺点是它要求指令以某种方式知道关于事件,因此必须有一些商定的事件接口。
 outerDirective = {
      link:function($scope, elem, attrs){  
           $scope.$on( 'decendentEvent', function( evt, data ){ ... })
      }
 }

 innerDirective = {
      link:function($scope, elem, attrs){  
           elem.bind('submit', function(){
               $scope.$emit( 'decendentEvent', { foo:123 })
           }
      }
 }