简体   繁体   中英

Calling javascript function from component AngularJS

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM