1

I'm building a sign up form, which will submit a user's input and then transit to a logged in state with template specific to this new user.

As far as I understand, to do this I have to use ng-submit() in html template together with $state.go() in controller.

Template:

<form ng-submit="register(name, password)">
  ...
  <input class="btn btn-success btn-lg btn-block" type="submit" value="Sign Up">
</form>

Controller:

angular.module('myApp').controller('RegisterController',
        ['$scope','userService', function($scope, userService) {
          $scope.register = function(name, passed) {
            userService.register(name, passed);
            $state.go("app.home");
          }
}])

However, there are only a few places I need to use $state.go(), in most cases, ui-sref in the html template is sufficient. Is this mixing of ui-sref and $state.go() a good practice? According to ui-router document, they essentially do the same thing. But with the state transition scattered in two different places (template and controller), it feels like a code smell to me.

I tried to use ui-sref and ng-submit together but it doesn't work, ng-submit gets ignored. What is the best practise in this case?

2 Answers 2

3

All ui-sref does is generate an href attribute with the URL for the specified state.

If you want to route somewhere on user interaction that can not be achieved with href (submitting the form in this case), you'll have to use $state.go.

You can just see it this way:

  • ui-sref: href attribute bound to an element.
  • $state.go transition to another state, controlled from your javascript code
Sign up to request clarification or add additional context in comments.

3 Comments

so does this mean mixing ui-sref and $state.go is a common practise?
Absolutely, don't see anything wrong with it, they just have different use cases
I see, previously all my state transitions are done via ui-sref and I can see all of them in html files which is quite clear, but now I'll need to go through javascript code to find all the state transitions, but as John Smith said there will be situations I have to use state.go, I guess this is the way to go then.
1

It is a good practice and in fact there isn't really any other way to do it. As you said you can't use ui-sref and ng-submit together which makes sense, you would be redirected to the new state.

Submitting a form via ng-submit is definitely the way to go, and $state.go is just a way to transition to another state in your controller.

There could be many situations where you have to transition to another state in your controller, so there is nothing wrong with mixing those two.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.