Setup
app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) {
$scope.data = $routeParams;
}]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/:url', {
template: '<h2>Hello World</h2>'
})
}]);
Layout
<body>
<div ng-controller="headerController">
Current Url:{{data.url}}
</div>
<div ng-view></div>
<ul>
<li>
<a href="#/pageA">Page A</a>
</li>
<li>
<a href="#/pageB>Page B</a>
</li>
</body>
Problem
I want the header section to constantly update with the current url everytime the route changes. When I load my app for the first time, this works. However, if I change the route, the controller does not update to the new url.
My question is not about solving this exact problem because I know there are other ways to do it, but rather solving it using this setup. In other words, I need to know how to provide a controller outside of a view with my current route, and have that controller update every time the route is changed.
You should try to make $scope.data a function to have it reevaluate.
Otherwise I suggest you listen to onRouteChangeSuccess to watch the URL change.
I tried your code and with some slight changes such as in the following, it is perfectly working on my side with firefox. The url correctly updates to Page A or Page B on change
I also may have not understood the question?
var app=angular.module('app',['ngRoute']);
app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) {
$scope.data = $routeParams;
}]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/:url', {
template: '<h2>Hello World</h2>'
})
}]);
<html ng-app="app">
<head>
<script src="angular.min.js"></script>
<script src="angular-route.js"></script>
<script src="controller.js"></script>
</head>
<body>
<div ng-controller="headerController">
Current Url:{{data.url}}
</div>
<div ng-view></div>
<ul>
<li>
<a href="#/pageA">Page A</a>
</li>
<li>
<a href="#/pageB">Page B</a>
</li>
</body>
Cheers
Nicolas
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.