0

I have one controller and two views.

ClustersContorller

angular.module('app.controllers').controller('ClustersController', [
  '$scope', 'ClustersService', function($scope, ClustersService) {
    ClustersService.getAll().success(function(data) {
      $scope.clusters = data;
    });
    $scope.$on('cluster:added', function(event, data) {
      ClustersService.createNew(data).then(
        function(res) {
          $scope.clusters.push(res.data);
        },
        function(res) {
          console.log( 'Unable to create a cluster!' );
        }
      );
    });
  }
]);

Now one view is working great when I send the HTTP request and update the scope variable by pushing to $scope.clusters:

<section class="clusters">
    <h2 ng-show="clusters.length < 1">You have no clusters :(</h2>
  <a class="btn btn-default btn-block" data-ng-repeat="cluster in clusters" data-template="{{cluster.templateId}}">
    <h2> {{ cluster.name }} </h2>
    <p> {{ cluster.description }} </p>
  </a>
    <add-cluster-modal></add-cluster-modal>
</section>

But the other view that is bound with this controller does not update scope.clusters in the bindings:

<ul class="dropdown-menu" role="menu" data-ng-controller="ClustersController">
  <li data-ng-repeat="cluster in clusters">
    <a> {{cluster.name}} </a>
  </li>
</ul>

Just to be clear the first view is bound by the $routeProvider and the second one is a part of a template included directly into the app main html file by ng-include=" 'templates/partials/header.html' "

Please feel free to ask me if something is confusing...

1 Answer 1

1

Angular controllers are not singletons, and every time you use ng-controller in a view, you create a new instance of that controller (see documentation). This is the reason why your second controller doesn't show the data - it's scope is not aware of the scopes of other instances.

You can either save the model's data under $rootScope, or create some eventing mechanism in your controller, that would inform other instances of data change.

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

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.