Faraj Farook
Faraj Farook

Reputation: 14885

How to access parent scope variables inside ui.route - onEnter method?

I'm using angularjs with angular ui route. In the parent state controller I have defined the scope variable dataset

How can I access the parent state scope within the child state onEnter method.

I tried this

.state('business.remove', {
     url: '/remove',
     onEnter: [...'$scope',...,
        function (...$scope,...) {
              ...
              $scope.$parent.dataset

But it gives an error

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope

Upvotes: 1

Views: 875

Answers (2)

GHB
GHB

Reputation: 947

Depending on your use of the variable, I think you might be able to do various things.

If you want to change it, you can use messaging from Lower to Upper scopes using $scope.$emit('eventName', {someData}) in lower scope, and $on('eventName', someFunction) inside parent scope and do the changing in your function.

But if you're trying to read the variable, you can either define that variable with $rootScope in parent and use it elsewhere, or define it inside a service then call the service and manipulate your data whenever needed...

In addition to these, you can go one step further with the first way(messaging), and send another message from parent scope to the child, using $broadcast and send that variable inside it to be read with $on inside the child scope... bud I don't know if it's a very optimized solution!

Hope that's helpful

Upvotes: 1

Chris T
Chris T

Reputation: 8216

In UI-Router, resolves should be used to load your applications primary data. Resolves can propagate down to child states, and are useful to manage lifecycle; They are loaded when a state is entered and go away when the state is exited. You can create a resolve on your parent state and inject it into the parent or child views (controller), and/or the onEnter/onExit hooks.

.state('business', {
 url: '/remove',
 resolve: { 
     dataset: function(someService) { 
        someService.fetchDataset();
     }
 },
 controller: function(dataset, $scope) {
    // do something with dataset
 }

.state('business.remove', {
 url: '/remove',
 onEnter: function (dataset) {
     // do something else with dataset

Upvotes: 0

Related Questions