Angular JS – Contollers and Valuesets (SPA Routing)

I can specify a controller for each state, to provide a model for its templates. An interesting thing is that I can use valuesets to call a state with a set of parameters. To do this I have to specify the valueset name in the state’s route (preceded by “:”). Then i have to pass the actual values as parameters when I’m creating the state link with the ui-sref directive (within a JSon object). This object is finally received by the controller of the target state as a parameter, so I can map its values on the $state object.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Angular JS</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body data-ng-app="myApp">
    <div class="container">
        <div class="row">
            <div class="col-md-12 well">
                <div ui-view="">
                </div>
            </div>
        </div>
    </div>
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <script src="Scripts/angular-ui-router.min.js"></script>
 
    <script>
        angular.module("myApp", ["ui.router"]).config(function ($stateProvider, $urlRouterProvider) {
 
            //Every undefined route
            //will be resolved with "/"
            $urlRouterProvider.otherwise("/");
 
            $stateProvider.state("root", {
                url: "/",
                template: "This is the home page"
                        + "<ul>"
                        + "<li><a ui-sref='detail({id: 1})'>Go to articleId 1</a></li>"
                        + "<li><a ui-sref='detail({id: 2})'>Go to articleId 2</a></li>"
                        + "<li><a ui-sref='detail({id: 3})'>Go to articleId 3</a></li>"
                        + "</ul>"
            }).state("detail", {
                url: "/detail/articleId/:id",
                template: "This is the detail page for articleId {{articleId}}"
                        + "<br/><a ui-sref='root'>Go to home</a>",
                controller: function ($scope, $stateParams) {
                    $scope.articleId = $stateParams.id;
                }
            });
        });
    </script>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s