Redplane
Redplane

Reputation: 3151

Event emitter callback in angularjs

I'm new to angularjs directive. Currently, I'm creating a sidebar directive:

'use strict';

angular.module('sidebar', ['ngRoute'])
    .directive('sidebar', function () {
        return {
            restrict: 'E',
            templateUrl: "components/sidebar/sidebar.html",
            controller: 'SidebarController',
            scope: {
                accountProfileName: '@',
                accountProfileImage: '@',
                accountProfileTitle: '@',
                items: '='
            }
        };
    })
    .controller('SidebarController', ['$scope', function ($scope) {
        $scope.clickDetail = function (item) {
            $scope.$emit("sidebarItemClick", item);
            console.log('Emitted');
        }
    }]);

<div class="profile-sidebar">
    <!-- SIDEBAR USERPIC -->
    <div class="profile-userpic">
        <img ng-src="{{accountProfileImage}}"
             src="{{accountProfileImage}}"
             class="img-responsive" alt="">
    </div>
    <!-- END SIDEBAR USERPIC -->
    <!-- SIDEBAR USER TITLE -->
    <div class="profile-usertitle">
        <div class="profile-usertitle-name">
            {{accountProfileName}}
        </div>
        <div class="profile-usertitle-job">
            {{accountProfileTitle}}
        </div>
    </div>
    <!-- END SIDEBAR USER TITLE -->
    <!-- SIDEBAR BUTTONS -->
    <div class="profile-userbuttons">
        <button type="button" class="btn btn-success btn-sm">Follow</button>
        <button type="button" class="btn btn-danger btn-sm">Message</button>
    </div>
    <!-- END SIDEBAR BUTTONS -->
    <!-- SIDEBAR MENU -->
    <div class="profile-usermenu">
        <ul class="nav">
            <li ng-repeat="item in items"
                ng-class="item.enabled ? 'active' : ''">
                <a href="javascript:void(0);"
                   ng-click="clickDetail(item)">
                    <i class="{{item.icon}}">
                        <span>{{item.title}}</span>
                    </i>
                </a>
            </li>
        </ul>
    </div>
</div>

In my index.html, I want to use this code:

<sidebar on-item-click="callbackOnItemClick($sidebarItem)"></sidebar>

I know how to use two way model binding, but I don't know how to use event emitter just like output in Angular 2.

Can anyone help me to do this please ?

Thank you,

Upvotes: 0

Views: 10643

Answers (1)

Manikandan Velayutham
Manikandan Velayutham

Reputation: 2228

Using $scope.$emit will fire an event up the $scope (like child ctrl to parent ctrl).

Using $scope.$broadcast will fire an event down the $scope (like parent ctrl to child ctrl).

Using $scope.$on is how we listen for these events(listen both $emitenter code here and $broadcast event).

https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Upvotes: 3

Related Questions