Monthly Archives: January 2015

UI-Router Dynamic States – Dynamically create states – List States

Writing boiler plate code for ui-router in angularjs isn’t required.

The code below dynamically creates states in ui-router the first time ui-router is called.

VIEWS, LIST, CREATE, VIEW, EDIT are constants defined in app.config.js.


$state.get(); // LISTS CURRENT STATES

// CONFIGURE STATES
var statesCtrls = [
{ state:'test', ctrl:"TestsCtrl" },
{ state:'tag', ctrl:"TagsCtrl" },
{ state:'tagType', ctrl:"TagTypesCtrl" }
];

function createState(stateCtrl){
var ctrl = stateCtrl.ctrl;
var state = stateCtrl.state;
var list = {
url: "/" + state ,
templateUrl: VIEWS + state + "-" + LIST + ".html",
controller: ctrl
};

var create = {
url: "/" + state + "/" + CREATE,
templateUrl: VIEWS + state + "-" + CREATE + ".html",
controller: ctrl
};

var view = {
url: "/" + state + "/:id",
templateUrl: VIEWS + state + "-" + VIEW + ".html",
controller: ctrl
};

var edit = {
url: "/" + state + "/" + EDIT + "/:id",
templateUrl: VIEWS + state + "-" + EDIT + ".html",
controller: ctrl
};

$stateProvider.state(state, list);
$stateProvider.state(state + "/" + CREATE, create);
$stateProvider.state(state + "/", view);
$stateProvider.state(state + "/" + EDIT + "/", edit);
}

angular.forEach(statesCtrls, function (stateCtrl) {
createState(stateCtrl);
});

$state.get(); // RELISTS CURRENT STATES