문제

I am creating an Angular.js app to consume the public Flickr API. I want to create a list/detail view of the most recent photographs on Flickr.

I am using a factory in Angular to supply data to two controllers. Here is the factory service:

angular.module('FlickrApp.services', []).
  factory('flickrAPIservice', function($http) {

      var flickrAPI = {};
      flickrAPI.getPhotos = function() {
        return $http({
          method: 'JSONP', 
          url: 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=JSON_CALLBACK'
        });
      }
    return flickrAPI;
  });

And here are the two controllers (one each for the list view and the detail view) that use the factory service:

angular.module('FlickrApp.controllers', []).
  controller('listController', function($scope, flickrAPIservice) {
    $scope.photosList = [];

    flickrAPIservice.getPhotos().success(function (response) {
        $scope.photosList = response.items;
    });
  }).
  controller('photoController', function($scope, flickrAPIservice) {
    flickrAPIservice.getPhotos().success(function (response) {
        $scope.photosList = response.items;
    });
  });

From the detail view, I create a link to the detail view based on the position of the photo in the array of items, this works fine:

<a class="title_link" href="#/photos/{{photosList.indexOf(item)}}">{{item.title}}</a>

However, because the list of photos is updated when the link to the detail view is called, the resulting view is not of the correct photo as the array is changed when the second controller uses the service.

What I would like to acheive would be to have the photosList populated once from the flickrAPIservice, then when that service was called from the second controller, to have it use the existing data, rather than going to get it all over again.

Should I put the photos into some kind of global array? I was trying to avoid this as I am pretty sure it's not the 'Angular way'?

Any help/suggestions would be much appreciated.

도움이 되었습니까?

해결책

Use scopal inheritance.

<div ng-controller="parentCtrl">
   <div ng-controller="childOneCtrl"></div>
   <div ng-controller="childTwoCtrl"></div>
</div> 

Store the array on the parent controller's scope like so :

  controller('parentCtrl', function($scope, flickrAPIservice) {
    $scope.photosList = [];

    flickrAPIservice.getPhotos().success(function (response) {
        $scope.photosList = response.items;
    });
  })

Then access it on the child controllers like so:

  controller('childOneCtrl', function($scope) {
    console.log($scope.photosList);
  }).controller('childTwoCtrl', function($scope) {
    console.log($scope.photosList);
  })

It will be there and should stay in sync as $digest is recessive through children.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top