0

I'm new to Angular's component and am trying to create header/footer for my website.

This is my current header component that I declared in the same file as my controller.

app.component('headerComponent', {

    template: '<div class="header"><div class="container"><div class="row">
    <div class="col-md-5"><!-- Logo --><div class="logo"><h1><a 
    href="adminHome.html">'+ localStorage.getItem('username')+'</a></h1>
    </div></div><div class="col-md-5"><div class="row"><div class="col-lg-
    12"></div></div></div><div class="col-md-2"><div class="navbar navbar-
    inverse" role="banner"><nav class="collapse navbar-collapse bs-navbar-
    collapse navbar-right" role="navigation"><ul class="nav navbar-nav"><li 
    class="dropdown"><a href="" class="dropdown-toggle" data-
    toggle="dropdown">My Account <b class="caret"></b></a><ul 
    class="dropdown-menu animated fadeInUp"><li><a 
    href="profile.html">Profile</a></li><li><a href ng-
    click="logout();">Logout</a></li></ul></li></ul></nav></div></div></div>
    </div></div>',

});

when i try to use the header component tags to include my header, my logout function does not work. How do I use a function that is declared outside of this component? Thanks!

1 Answer 1

1

Just being in the same file will not be enough. When you define the component, you need to tell angularJs what controller to use, or it will use a default controller (which is basically an empty function). Additionally, components use controller-as syntax, so you can't just call logout(), you need to call $ctrl.logout(). So for example:

// I did the controller as a constructor function, but you could also do a class
const MyController = function ($log) {
   this.logout = function () {
      $log.info('you clicked the logout button!);
   }
}

app.component('headerComponent', {
    template: '<a ng-click="$ctrl.logout()">hello world</a>,
    controller: MyController
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Its working now after adding the controller. Also, if it is possible to use a function that is not declared in the controller? One that exist in a html script tags

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.