1

I am receiving object data from one JSON request, similar to this:

{
  "slides": [
    {
      "image": "http://lorempizza.com/380/240",
      "title": "Slide aa",
      "description": "I owe you the description"
    },{
      "image": "http://lorempizza.com/380/240",
      "title": "Slide bb",
      "description": "I owe you the description"
    }
  ],
  "title": "Interesting object",
  "description": "Lorem ipsum dolor sit amet consectetur."
}

I want to use two different views. One for the slides and another one for the title and description of the object, everything on the same page. Why? Because I'm using ui views to display them.

index.html

<div ui-view="slider"></div><!-- Here is the slider -->
<main ui-view role="main"></main><!-- Here is title and desc -->

The problem is here:

slider.html

<div ng-controller="InterestingObjectCtrl">
    <!-- Display slider -->
</div>

main.html

<div ng-controller="InterestingObjectCtrl">
    <!-- Display title and desc -->
</div>

InterestingObjectCtrl.js

InterestingService.get()
    .success(function(data) {
      $timeout(function() {
        $scope.$apply(function() {
          $scope.interestingObject = data;
        });
      });
    })

The InterestingObjectCtrl controller will load twice the same JSON making useless HTTP requests.

What would be the right way or "angular way" to solve this?


Setting a flag (like if ($scope.requestAlreadyMade) return;) will definitely won't work.

The HTTP requests may not be a big deal caching the $http service, but that is far from the point of this problem.

Calling the controller as a wrapper, like the following example, will make it be loaded from every page on the website, which is even worst.

<div ng-controller="InterestingObjectCtrl">
  <div ui-view="slider"></div><!-- Here is the slider -->
  <main ui-view role="main"></main><!-- Here is title and desc -->
</div>
Community
  • 1
  • 1
Lucio
  • 4,753
  • 3
  • 48
  • 77
  • Meanwhile, take a look at angular ui router's way of solving this: https://github.com/angular-ui/ui-router/wiki#resolve – idursun Oct 09 '14 at 08:43

1 Answers1

0
   <div ng-controller="MainCtrl">
         <div ui-view="slider"></div><!-- Here is the slider -->
         <main ui-view role="main"></main><!-- Here is title and desc -->
    </div>

load data once in MainCtrl and breadcast it to child controllers:

InterestingService.get()
    .success(function(data) {
      $scope.$broadcast('dataloaded', data);
    });

InterestingObjectCtrl.js

$scope.$on('dataloaded', function (data) {
// do what you want
});
Marian Ban
  • 8,158
  • 1
  • 32
  • 45
  • I will be forced to load the controller on every page of the web site. That is what I'm trying to avoid. – Lucio Oct 09 '14 at 06:40
  • @Lucio i thought you asked for solution for "The InterestingObjectCtrl controller will load twice the same JSON". With MainCtrl you will load it only once. – Marian Ban Oct 09 '14 at 06:45