How do i access the new $scope after moving with $state.go() in AngularJS UI Router

Issue

Hey guys im trying to reach the new scope after i changed the state with $state.go.

$state.go("newState").then(function () {
      // doesn't work
     $state.current.$scope.variable = "abc";
     
     // doesn't work as well because it's referencing the old $scope
     $scope.variable = "def";
                })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Solution

You could pass the variable in the state change instead

$state.go("newState", {variable: "abc"})

Add the params in the state config

$stateProvider
.state('newState', {
    url: '/newState',
    params: {
        variable : null
    },
    templateUrl: 'newState.html',
    controller: 'newStateCtrl'
});

Then in your newStateCtrl, inject $stateParams and get the variable

$stateParams.variable

Answered By – Marcus Höglund

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.