Search code examples
angularjsangularjs-scopeangularjs-injector

AngularJS access parent scope


I'm new to angularjs and I'm trying to do some things that I don't know if is a good practice.

Well, I have a main page where I want to show the messages of all other controller and views.

In this "main" view I have the following

<div class="row" data-ng-repeat="msg in messages">
    <div class="col-lg-12">{{mgs.message}} 
        <a data-ng-click="close(msg)">&times;</a>
    </div>
</div>

When I set a message in my MainController the message is shown, but when I navigate to another controller it isn't.

Google told me that it happens because I'm working with different scopes.

I would like to know:

  • How do I add messages into the "parent" scope? or
  • How do I call a method of MainController inside my Functionality2Controller or
  • What are the other better ways to show messages in the main page?

Solution

  • Different controller use different scopes and thats right and you should try to change that. First thing you could do is using the $rootScope, where all other scopes are derivated from. But that kind of a misuse, the imo better solution is creating a shared messageService:

    .factory('messageService', [
      function() {
        var messages = [];
    
        return {
          getMessages: function() {
            return messages;
          },
          addMessage: function(message) {
            messages.push(message)
          }
        }
      }
    ])
    

    and inject it to your controller:

    .controller('ctrl', ['$scope', 'messageService',
      function($scope, messageService) {
        $scope.messages = messageService.getMessages();
      }
    ])
    

    Plunker: http://plnkr.co/edit/6cnbx9okRA03tut7JzuF?p=preview