aleczandru
aleczandru

Reputation: 5459

Angular ng-click not executing function inside a custom directive

I have created a custom directive and added a controller to it and a function on the state hamburgerClick.Here is my code:

 directivesModule.directive('headerDir', [function () {
    var headerDir = {
        restrict: 'E',
        templateUrl: 'App/scripts/main/directives/header/HeaderDir.html',
        replace: true
    };

    headerDir.controller = ['$state', function ($state) {
        $state.hamburgerClick = function() {
            var app = $('.application-wrap');
            if (app.hasClass('menu-opened')) {
                app.removeClass('menu-opened');
            }
            else {
                app.addClass('menu-opened');
            }
        };
    }];

    return headerDir;
}]);

<div>
<span class="menu-overlay"></span>
<section class="menu-bar">
    <article>
        <div class="menu-button" ng-click="hamburgerClick()">
            <span class="hamburger-icon"></span>
        </div>
        <h1 class="logo"></h1>
    </article>
</section>

My problem is that for some reason the function does not get executed when I am trying to click on it.ANyone know what I am doing wrong?

Upvotes: 0

Views: 371

Answers (2)

pokaxperia
pokaxperia

Reputation: 87

Try this!

directivesModule.directive('headerDir', [function () {
    return{
        restrict: 'E',
        templateUrl: 'App/scripts/main/directives/header/HeaderDir.html',
        replace: true
        controller: function($scope){
            $scope.hamburgerClick = function() {
                var app = $('.application-wrap');
                $('.application-wrap').toggleClass('menu-opened');
            };
        }
    }
}]);

Upvotes: 1

rcijvat
rcijvat

Reputation: 182

There are several things doubtful in your code

1) You should replace $state with $scope

2) You do not use your directive inside your HTML code. Instead, you refer to a directive named 'article'

3) You use replace:true, which replaces the original content of the directive. Unless you planned on defining your $('.menu-button') as header-dir directive, the call to hamburgerClick will be removed.

Furthermore, you could replace

var app = $('.application-wrap');
if (app.hasClass('menu-opened')) {
    app.removeClass('menu-opened');
}
else {
    app.addClass('menu-opened');
}

with

$('.application-wrap').toggleClass('menu-opened');

Upvotes: 1

Related Questions