javascriptangularjsangularjs-directivefrontendfront-end-optimization

Calling Functions from AngularJs Directive


I need to insert a header in my AngularJS application.

I used to have a header and header controller containing login/logout functions since the header contains the username and login/logout.

Now I changed this to header directive, but in order to use the header in all the application pages I have to repeat writing the login/logout function and get the username in all the other pages controllers which is obviously repetitive and inefficient.

I'm new to AngularJS so I wonder if there is a good practice to solve this issue. May I write these functions in the directive itself instead and just pass the username from the controllers, is it a good practice?


Solution

  • You just have to create a service with login/logout functions.

    Then you just have to inject your service in your directive.

    Take a look here : https://docs.angularjs.org/guide/services