ProllyGeek
ProllyGeek

Reputation: 15856

Angular ui-router stateProvider as chainable object

Angular UI-Router is a routing framework, when I was searching for how to use UI router I found two approaches for using it, the async state method invoke, and the sync state method invoke as in:

Sync:

$stateProvider
    .state('state1', {
      url: "/state1",
      templateUrl: "partials/state1.html"
    })
    .state('state1.list', {
      url: "/list",
      templateUrl: "partials/state1.list.html",
      controller: function($scope) {
        $scope.items = ["A", "List", "Of", "Items"];
      }
    })
    .state('state2', {
      url: "/state2",
      templateUrl: "partials/state2.html"
    })
    .state('state2.list', {
      url: "/list",
      templateUrl: "partials/state2.list.html",
      controller: function($scope) {
        $scope.things = ["A", "Set", "Of", "Things"];
      }
    });
});

Async:

$stateProvider
    .state('state1', {
      url: "/state1",
      templateUrl: "partials/state1.html"
    });
$stateProvider
    .state('state2', {
      url: "/state2",
      templateUrl: "partials/state2.html"
    })

the question is there any difference between two methods, and is any method better than other, and why?

Upvotes: 1

Views: 59

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123901

I would say, that there is NO async or sync syntax. It is just a fluent syntax.

The method $stateProvider.state(...), has this implementation,

state.js

function state(name, definition) {
    /*jshint validthis: true */
    if (isObject(name)) definition = name;
    else definition.name = name;
    registerState(definition);
    return this;
}

where the most important is last line - return this;. That is just a fluent syntax:

Fluent interface

... A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining). Generally, the context is

  • defined through the return value of a called method
  • ...

Other words, these are the same:

// not fluent syntax
$stateProvider.state(name1, {..}) // returned value not used
$stateProvider.state(name2, {..}) // returned value not used

// fluent in place
$stateProvider
   .state(name1, {..}) // returned value is $stateProvider again
   .state(name2, {..}) // returned value not used

Upvotes: 2

Related Questions