0

I want to create a directive of a sidebar. I have function in the controller that toggles the sidebar.

How can I access this function from any other controller in my application?

Thanks!

2 Answers 2

1

If you want to manipulate with your SideBar from whole your application, it is probably better way to save the state of SideBar in the Service. So you will have access to this service whenever you inject it, and you will able to change state of SideBar by changing this related Service value (It is possible because Services are always have only one instance, like Singleton pattern).

So, I will attach image which will show basic communication pattern for current case.

Controllers communication via service

If we will change the state of active variable in the State Service, the SideBar Directive will be affected, because all three controllers are linked to the same instance of service.

Here Controllers service communication is small example of communication between controllers via service.

Hope it will help you!

Sign up to request clarification or add additional context in comments.

Comments

1

I have function in the controller that toggles the sidebar

Its´not recomended to use any UI logic inside Controllers. In the World of Angular these things can be achieved by using declerative HTML.

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
  <div ng-show="isReplyFormOpen" id="replyForm"></div>

To answer your question: You can define a service which contains your function.

(function(){
  angular.module('YourApp')
    .factory('ToggleBar', function(){
       function anyFunc(){
       //Logic here...
       }

       return{
         toggle: anyFunc
       };
  });
)();

Than inject the service to any Controller you whant to.

(function(){
   angular.module('YourApp')
     .controller('ControllerName',['ToggleBar',function(ToggleBar){
       //Call the service func...
       ToggleBar.toggle();
     }]);
)();

Comments

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.