0

I'm trying to follow John Papa's guidelines, in which he explains how using this combined with controllerAs is preferable to $scope.

The problem is that I can't find an easy way to get a variable (user) defined in ParentController (vm.user) and use it, even transform it in a ChildController.

Code for illustration :

controllers.js

 app.controller('ParentController', function() {
     var vm = this;
     vm.user = {firstName:"John", lastName:"doe"};
 });

app.controller('ChildController', function() {
     var vm = this;
     /* How can I access 'vm.user' defined in ParentController
        without using $scope as John Papa's suggests ? */
 });

index.html

<div ng-controller="ParentController as parent">
    <div ng-controller="ChildController as child">
</div>

I could just put everything in one big controller but I want to keep my code clean and readable.

Thanks!

2
  • 1
    Some code would help to understand what's your problem. Commented Oct 27, 2015 at 10:51
  • @jjimenez I edited my answer with some code Commented Oct 27, 2015 at 10:58

1 Answer 1

3

You shouldn't access data from one controller to another, it's not a good practice. In order to share data between controllers, you should use a service.

Here you have JSBin with an example.

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

2 Comments

There is no equivalent to $scope ? Because inheritance doesn't seem a bad practice, is it ?
OK now I understand the spirit. Thanks for your JSBin.

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.