Search code examples
javascriptangularjsangular-ui-routerangular-ui

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


Solution

  • 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