简体   繁体   English

从组件AngularJS调用javascript函数

[英]Calling javascript function from component AngularJS

I'm new to Angular's component and am trying to create header/footer for my website. 我是Angular组件的新手,正在尝试为我的网站创建页眉/页脚。

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). 定义组件时,需要告诉angularJs使用哪个控制器,否则它将使用默认控制器(基本上是一个空函数)。 Additionally, components use controller-as syntax, so you can't just call logout() , you need to call $ctrl.logout() . 另外,组件使用controller-as语法,因此您不仅可以调用logout() ,还需要调用$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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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