1

I have this plunkr. I define two controllers: mainController and itemsController. I want to access to the scope variable items from a view, but I can't.

To reproduce, you need to click first in the button Populate Items, (the array item is populated from a service) and you see in the console the values. Then click in the button Say Hello ! and then you will see that items is empty; but, the variable tab is being accessed.

I think that I'm not applying in the correct way the definitions of the controllers.

1 Answer 1

1

There is updated and working plunker

What we need, is the data sharing:

How do I share $scope data between states in angularjs ui-router?

so instead of this

  app.controller("itemsController", 
   function($rootScope, $scope, $state, $stateParams, Data) {
    $scope.items = []; // local reference, not shared

    $scope.getFromJson = function() {
      Data.get().then(function handleResolve(resp) {
        $scope.items = resp;
        console.log($scope.items);
      });
    };
  })

we will fill the shared reference $scope.Model.items = resp;

  app.controller("itemsController", 
   function($rootScope, $scope, $state, $stateParams, Data) {

    $scope.getFromJson = function() {
      Data.get().then(function handleResolve(resp) {
        $scope.Model.items = resp;
        console.log($scope.Model.items);
      });
    };
  })

which will be hooked on the super root home. So, instead of this:

$stateProvider
  .state("home", {
    abtract: true,
    url: "/home",
    resolve: {
      $title: function() {
        return 'Tab1';
      }
    },
    views: {
      "viewA": {
        templateUrl: "home.html"
      }
    }
  });

we will have that:

  .state("home", {
    abtract: true,
    url: "/home",
    resolve: {
      $title: function() {
        return 'Tab1';
      }
    },
    views: {
      "viewA": {
        templateUrl: "home.html",
        // HERE we do the magic
        // this is a super parent view
        // at which $scope we will have shared reference Model
        controller: function($scope){
          $scope.Model = {}
        }
      }
    }
  });

check it in action here

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

1 Comment

This is amazing and very interesting ! Thanks again for your help !

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.