Go to a view and trigger a $scope function with ui-router

Issue

I realize this ask is for a hack, but here is the motivation:

  • I am designing a “shortcut” view for my rather complex app. Users want to trigger functions inside different views.
  • Different users have different opinions on useful shortcuts
  • For example, one user may want to define a shortcut that “goes to view app.montage and triggers $scope.toggleInfo()
  • Another user may want to define a completely different shortcut that invokes a function 3 levels deep inside an existing view’s UI

So bottomline, can I devise something like:
$state.go('state name') && then initiate function inside that state?

I know I can define URL routes, but its a rather complex app and its easier to be able to “trigger” actions if I can.

Solution

$stateProvider.state('users', {
    url: '/users',
    controller: 'UsersCtrl',
    params: {
        obj: null
    }
})
function UserCtrl($stateParams,$scope) {
    console.log($stateParams);
    $stateParams.obj && $stateParams.obj.toggleInfo && $scope.toggleInfo();
}
$state.go('users', {obj:{toggleInfo: true});

For more information, see UI-Router Wiki – Using Parameters without Specifying Them in State URLs.

Answered By – georgeawg

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.