angularjs - Angular.js: Adding a simple route to a demo app? -
i building simple demo angular application, see how compares backbone, , i've got stuck when comes routing, although i've read routing tutorial.
i'd route in demo app update whenever <select>
element changes, /lhr
or /sfo
or whatever new value of select (and presumably /#lhr
etc in browsers without history api).
i'd router handle initial path when page loads, , set default value of <select>
option.
here html - have 1 template:
<html ng-app="angularapp"> [...] <body ng-controller="appctrl"> <select ng-model="airport" ng-options="item.value item.name item in airportoptions" ng-change='newairport(airport)'></select> <p>current value: {{airport}}</p> </body></html>
and here js in full:
var angularapp = angular.module('angularapp', []). config(['$routeprovider', function($routeprovider) { $routeprovider. when('/:airportid', {templateurl: 'angular.html', controller: appctrl}). otherwise({redirectto: '/'}); }]); angularapp.controller('appctrl', function appctrl ($scope, $http, $routeparams) { $scope.airportoptions = [ { name: 'london heathrow', value: 'lhr' }, { name: 'san francisco international', value: 'sfo' }, { name: 'paris charles de gaulle', value: 'cdg' } ]; $scope.airport = $scope.airportoptions[0].value; // or route if provided $scope.newairport = function(newairport) { console.log('newairport', newairport); }; });
i'm not @ sure i've set route provider correctly, , it's giving me uncaught referenceerror: appctrl not defined angularapp
. doing wrong?
update: fixed referenceerror putting appctrl in quotes, commenter. problem $routeparams
empty when try navigate /#lhr
. how can route parameter?
update 2: got route working - feels bit hacky though. doing right?
var angularapp = angular.module('angularapp', []); angularapp.config(function($routeprovider, $locationprovider) { $routeprovider. when('/:airportid', {templateurl: 'angular.html', controller: "appctrl"}). otherwise({redirectto: '/'}); }); angularapp.controller('appctrl', function appctrl ($scope, $routeparams, $location) { $scope.airportoptions = [ { name: 'london heathrow', value: 'lhr' }, { name: 'san francisco international', value: 'sfo' }, { name: 'paris charles de gaulle', value: 'cdg' } ]; var starting_scope = null; ($location.path()) ? starting_scope = $location.path().substr(1) : starting_scope = $scope.airportoptions[0].value; $scope.airport = starting_scope; $scope.newleague = function(newleague) { $location.path("/" + newleague); }
Comments
Post a Comment