My goal is to construct a simple Angular application and familiarize myself with the basics.
To start, I'm utilizing Yeoman's angular-generator
for scaffolding. This generator comes with a predetermined .config
featuring $routeProvider
, which I tweaked to suit my requirements:
angular
.module('raidersApp', [
'ngRoute',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/:langID/:proverbID', {
templateUrl: 'views/proverb.html',
controller: 'ProverbCtrl'
})
.when('/:langID', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/en'
});
});
In order to maintain organization, I've designed several templates that will be included in my app's index.html
:
<header class="header" ng-controller="HeaderCtrl">
<div ng-include="'views/header.html'"></div>
</header>
<main class="container">
<div ng-view=""></div>
</main>
<footer class="footer">
<div ng-include="'views/footer.html'"></div>
</footer>
Within the header view, there is a Bootstrap navbar that requires dynamic content based on user input. The ID of the selected language is obtained using $routeParams
:
<li class="dropdown">
<a href class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{langID}}<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#/{{language}}" ng-repeat="language in languages">{{language}}</a></li>
</ul>
</li>
To ensure this value can be accessed by multiple controllers, I created a data
factory:
angular.module('raidersApp')
.factory('data', function () {
var langID = "en";
return {
getLang: function() {
return langID;
},
setLang: function(newlangID) {
langID = newlangID;
}
}
});
I developed a separate controller, HeaderCtrl
, to manage the navbar:
angular.module('raidersApp')
.controller('HeaderCtrl', function (data, $http, $scope, $routeParams) {
$scope.langID = data.getLang();
$scope.languages = [
'en',
'pt',
'se'
];
});
However, the controller is only invoked once. As a result, the default language (in this case, "en"
) remains static in the dropdown menu.
While the rest of the functionality works as intended, including URL navigation and language updates in the main controller via $routeParams
, the issue lies specifically with the header controller.
One potential explanation could be that the HeaderCtrl
is defined outside the ng-view
scope in the index.html
, causing it to be disregarded by the $routeProvider
.
How can I address this dilemma without duplicating the navbar across all views?
I considered incorporating ng-include
in each template, but this approach feels inelegant. Are there cleaner or more sophisticated solutions available?