swang
swang

Reputation: 5249

Mix ui-sref and $state.go for state transition in Angular ui-router

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?

Upvotes: 1

Views: 567

Answers (2)

John Smith
John Smith

Reputation: 2341

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.

Upvotes: 1

Robin-Hoodie
Robin-Hoodie

Reputation: 4974

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

Upvotes: 3

Related Questions