1

I'm using ionic: I created a "Notification" directive that does some preprocessing to determine what type of notification ('alert', 'message' or 'important message') to display base on an object passed in an attribute. Within the template of that directive I am calling another directive called "Update Notification" - this is an item option that is revealed when the user slides the item to the left and (is supposed to) calls an update modal with a form who's model is passed through an attribute "notification."

The problem I'm having is that the template of "Update Notification" is calling showUpdateNotification() but it seems to be calling the "Notification" directive's scope functions; even though the "Update Notification" directive has a defined scope.

I want to define the update functionality in the "Update Notification" directive to be able to call it elsewhere in the app with another template, but I'm not sure how to resolve my scope issue.

Thanks for your help!

Notification Directive:

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

Notification Template:

<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>

Update Notification Directive:

.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();

            };
        }
    };
});

Update Notification Template:

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

Here is a Plunker (sorry the Sass didnt translate well - looks crappy)

  • can you put this on jsfiddle or plunker or something so we can work through it? – jusopi Oct 17 '16 at 14:28
  • @jusopi I'm not sure how to do that to be honest. – rcpilotp51 Oct 17 '16 at 15:00
  • I know nothing of Ionic but Angular works fine on both of those resources. Just recreate the DOM and code on one of them and then post the link back. It's probably the best way for folks to help you. – jusopi Oct 17 '16 at 15:02
  • @jusopi do you follow my question...i cant get it to work on either platform...jsfiddle or plunker... – rcpilotp51 Oct 17 '16 at 15:46
  • @jusopi embed.plnkr.co/fEh1yLkT2Bqqq9ua065K – rcpilotp51 Oct 21 '16 at 16:45
1

I wasn't able to really find my way around your example so rather than providing an answer specific to your example, I will present the way most people achieve directive-to-directive communication.

SCOPE-CALLBACK

This is probably the most used means to communication from an inner scope to an outer entity. Note I said "outer entity" instead of "outer scope". This is because it's not exclusive to directive-to-directive communication. In the inner directive, you establish a callback like so:

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

You declare this in a template where the directive is used, where doSomething is a method defined on your controller:

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

or with the callback params

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

REAL DIRECTIVE-to-DIRECTIVE COMMUNICATION VIA require

A more sophisticated way of having directives communicate with one another is using the require field when defining your directive. You see this used all the time when a custom directive requires a ng-model for an input. Example:

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

In the above example the directive has access to the ngModelController APIs that are required. In your case, you can define a controller on your outer directive and then require it in your inner directive:

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

In this case, I just declared the inner directive inside the outer directive's template for brevity.

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

EVENT BUS

This is a classic way of communicating with various constituents of MVC frameworks across many different technologies and languages. It's certainly not THE angular way of doing things and I normally wouldn't recommend this method unless you can't get anything else to work. It's also subject to scope hierarchy. Lastly, its main drawback is that it requires that the directives know about the events in some way, so there has to be some agreed upon event interface.

 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 })
           }
      }
 }
|improve this answer|||||
  • Am I wrong to assume that you are calling a function on the outer directive from the inner directive in this case? I simply want the inner directive to call its own functions. – rcpilotp51 Oct 24 '16 at 16:30
  • All 3 of these are means to communicate betw. entities. If you want a directive to call its own functions, then it needs a) to be an isolate scope in most cases and b) defined methods on a controller. and c) highly recommend you use controller as syntax. – jusopi Oct 24 '16 at 18:27
  • my confusion is: thats what I thought I did; I would like to know where I went wrong, because it is not clear to me – rcpilotp51 Oct 24 '16 at 18:30
  • I offer this criticism only in the effort for you to solve your issue, but that was NOT clear to me at all by the question/example. Even if you clearly stated that, it got lost in with the wealth of information you provided. I'd do this: Create a new question, very basic example, get 2 directives from scratch, don't muddy the waters with the ION lib or anything else. See if that helps you identify the error. Again, this isn't a complaint, just I feel I wasn't able to offer you anything because I couldn't discern the issue clearly. – jusopi Oct 24 '16 at 18:52
  • element.bind('click',function(){}); doesnt seem to be firing either on the inner directive. – rcpilotp51 Oct 24 '16 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.