cyberfly
cyberfly

Reputation: 5878

How to perform same logic for every AngularJS UI route if having certain GET parameter?

I have this condition that I want to solve:

1.User visit link test.dev/hello?user=Ali will show alert "Hi Ali"

2.User visit link test.dev/about?user=Ali will show alert "Hi Ali"

In short, for every ROUTES that I have, I want to perform GET parameter USER and show it

For example, this is my sample routes taken from internet:

var myApp = angular.module('helloworld', ['ui.router']);

myApp.config(function($stateProvider) {
  var helloState = {
    name: 'hello',
    url: '/hello',
    controller: helloController,
    template: '<h3>hello world!</h3>'
  }

  var aboutState = {
    name: 'about',
    url: '/about',
    controller: aboutController,
    template: '<h3>Its the UI-Router hello world app!</h3>'
  }

  $stateProvider.state(helloState);
  $stateProvider.state(aboutState);
});

Current solution:

  1. Create a Notification Service, with function notifyUser() that will get the StateParams and alert it
  2. Inject NotificationService to all Routes Controller, and call the notifyUser()
  3. Keep repeating Step 2 if there is any new Route Controller

Problem:

I found this current solution that I implement is not DRY, because I need to repeating Step 2 for every new Controller that havent implemented it.

Read somewhere we can use RootScope and called the service inside RootScope, but still we need to call the notifyUser() in each Controller.

Question:

Is there a better way to handle this condition? How do we achieve it while keeping DRY?

Thanks for your insight

Upvotes: 0

Views: 44

Answers (1)

31piy
31piy

Reputation: 23859

You can define a transition hook and perform your action there.

$transitions.onSuccess({}, function(transition) {
  ...
});

The callback has access to one parameter, which is a transition object. You can explore it, and can get the value of the query parameter using it.


Edit 1:

If you're using older version of UI Router, you can take advantage of State Change Events to do the same thing. You need to define a change listener on the root scope:

$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
  ...
});

Upvotes: 0

Related Questions