Something I threw together today was the ability to hit this route:
http://localhost/whatever/index.htm#/foo/13
...and get the following back in an AngularJS application:
13
1313
It comes up in a web page. The piece of HTML is in a template. The templates are summoned into a div which is a piece of a greater .html page which holds the navigation for the application. Think master pages in ASP.NET. Anyways, the most important bit of our master page is:
<div id="page-wrapper" ui-view></div>
We use the following controller. The .js file containing the controller gets referenced in the "master page" so that the controller may be found.
assetControllers.controller('fooCtrl', ['$scope', '$state', '$stateParams', '$modal',
function fooCtrl($scope, $state, $stateParams, $modal) {
var myid = $stateParams.id;
$scope.things = [];
$scope.things.push({asgiven: myid, asaddedtoself: myid + myid});
}]);
The template:
<h1 class="page-header">Foo!</h1>
<div ng-repeat="thing in things">
{{thing.asgiven}}
<br />
{{thing.asaddedtoself}}
</div>
I was at first surprised that 13 + 13 equaled 1313 instead of 26, but I suppose I should not be. Everything that comes over the URL line is going to be a string. If I needed 13 to be an integer, I would have had to do some casting in my controller. How do the template and the controller get found to begin with? Well, there has to be a list of routes in app.js. It will look like so:
adminApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/bar");
$stateProvider
.state('foo', {
url: "/foo/:id",
templateUrl: "templates/foo.html",
controller: 'fooCtrl'
})
.state('bar', {
url: "/bar",
templateUrl: "templates/bar.html",
controller: 'barCtrl'
})
.state('baz', {
url: "/baz",
templateUrl: "templates/baz.html",
controller: 'bazCtrl'
})
.state('qux', {
url: "/qux",
templateUrl: "templates/qux.html",
controller: 'quxCtrl'
});
});
Yay!
No comments:
Post a Comment