Chapter 19, Accessing the URL (Pro AngularJS)

by js_test

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<body ng-app="exampleApp" ng-controller="defaultCtrl">
    <div class="panel panel-default">
        
<h4 class="panel-heading">URL</h4>

        <div class="panel-body">
            <p>The URL is: {{url}}</p>
            <div class="btn-group ">
                <button class="btn btn-primary" ng-click="setUrl('reset')">Reset</button>
                <button class="btn btn-primary" ng-click="setUrl('path')">Path</button>
                <button class="btn btn-primary" ng-click="setUrl('hash')">Hash</button>
                <button class="btn btn-primary" ng-click="setUrl('search')">Search</button>
                <button class="btn btn-primary" ng-click="setUrl('url')">URL</button>
            </div>
        </div>
    </div>
</body>

JavaScript

angular.module("exampleApp", [])
    .config(function ($locationProvider) {
    if (window.history && history.pushState) {
        $locationProvider.html5Mode(true);
    }
}).controller("defaultCtrl", function ($scope, $location) {
    $scope.$on("$locationChangeSuccess", function (event, newUrl) {
        $scope.url = newUrl;
    });
    $scope.setUrl = function (component) {
        switch (component) {
            case "reset":
                $location.path("");
                $location.hash("");
                $location.search("");
                break;
            case "path":
                $location.path("/cities/london");
                break;
            case "hash":
                $location.hash("north");
                break;
            case "search":
                $location.search("select", "hotels");
                break;
            case "url":
                $location.url("/cities/london?select=hotels#north");
                break;
        }
    }
});