-1

Somewhat related : Angular - ui-router get previous state.

I have search results view. Obviously, it makes no sense for the user to enter this URL into the browser's address bar & navigate there.

I would like to detect if (s)he does so & issue an admonition.

But, how? If a user goes directly there, there is no state transition. So, how do I detect it?

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • What is the ui-router version ? And also, what do you mean `there is no state transition`, isn't it a separate state? – Bill P Mar 03 '20 at 13:05
  • I am using the latest version. Will add the version number when I get home this evening. By "no state transition", I mean that if you just enter a state in the browser's URL bar, you are not transitioning from one ui-router state to another. – Mawg says reinstate Monica Mar 03 '20 at 13:31
  • What you want to achieve is to prevent user navigate to a view from the address bar? (and only go there from a button action?) – Bill P Mar 03 '20 at 13:48

2 Answers2

1

When user enters url manually - your app is re-inited, so use app.run to track location:

app.module('myModule').run(['$location'], ($location) => {
     if ($location.path().startsWith('/search')) {
       alert('bad boy')
     }
})

Or first state change to track state name:

app.module('myModule').run(['$transitions'], ($transitions) => {
     const deregister = $transitions.onSuccess({}, (transition) => {
        if (transition.to().name === 'search') {
            alert('bad girl')
        }
        deregister();
     })
})
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
0

I settled for a service, which I already use to share data between controllers , when changing state. The reason being that transition state change OnSuccess() does not work the first time, as per

https://github.com/angular-ui/ui-router/issues/3536 and may others

// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=++=+=+=+=+=+=+=+=+=+=+=
Self.setState = function (currentState, newState) {
    Self.setPreviousState(currentState);
    console.log("Change state from [" + currentState + "] to [" + newState + "]");
    Self.state = newState;
    $state.go(newState);
}

// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=++=+=+=+=+=+=+=+=+=+=+=
Self.getState = function () {
    console.log("Current state is [" + Self.state) + "]";
    return Self.state;
}

// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
Self.getPreviousState = function () {
    return Self.previousState;
}
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
Self.setPreviousState = function (previousState) {
    Self.previousState = previousState;
}
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551