0

The situation:

- Controller1 handles data related to posts on Page 1.

- Controller2 handles data related to comments to posts above, on Page 2.

{{comments.length}} works on a page 2 that has "Controller2"`but not work in page 1. I read about shared service and was wondering how to insert the service in this case?

Im not trying to have both controllers reflect a same object name that will reflect 2 different values under 2 different controllers. I hope to make {{comments.length}} workable in page 1.


Controller1

app.controller('PostsCtrl', function($scope, Post, Auth) {   //insert Shared here

  $scope.posts = Post.all;
  $scope.user = Auth.user;


Controller 2

app.controller('PostViewCtrl', function($scope, Post, Auth, $stateParams) { //insert Shared here

    $scope.post = Post.get($stateParams.postId);
    $scope.comments = Post.comments($stateParams.postId);


Shared service

app.service('Shared', function() {
  return {   //notsure what to insert here since theres no data field
  };
});

I noted a solution of a service that shares 2 controllers on SO:

AngularJS: How can I pass variables between controllers?

Would this be the best solution and are there any other easier means to do this?

Community
  • 1
  • 1
Thinkerer
  • 1,586
  • 4
  • 22
  • 42
  • $rootScope is easy but messy, I would use a shared service/factory - http://plnkr.co/edit/xf803TfFIXrVKsnpai1e?p=preview. If you handle the object this way you can also bind without getter/setter like the other example. – Dylan Nov 16 '14 at 21:15
  • Thanks @Dylan . i have something on rootscope and it totally messes my scopes. What do you mean by no need for getter/ setter? – Thinkerer Nov 17 '14 at 03:03
  • I just meant if you compare my example plunker - to the getProperty / setProperty example you listed. The binding is done on the object so the extra code seems unneeded. – Dylan Nov 17 '14 at 07:55

0 Answers0