Alex
Alex

Reputation: 2959

Why the controller isn't called when I manually reload the page? And how to fix it?

I work with angular.js. I Have a list of item and when I click on one of them it should display a specific template.

Everything works if I'm using the app from the root (index.html) but after clicking an item, if I reload the page (with the modified URL), the controller isn't call even if I try to click on the same item again.

Here is my code:

config.js

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/building/:buildingName', {
            templateUrl: 'views/building.html',   
            controller: 'buildingCtrl'
        })
        .otherwise({redirectTo: '/'});
}]);

townCtrl.js

app.controller('townCtrl', ['$scope', '$routeParams',
    function ($scope, $routeParams) {    
        $scope.buildingsList = [{
            name: 'Foo',
            route: 'foo'
        }, {
            name: 'Bar',
            route: 'bar'
        }];

        $scope.select = function (item) {
            $scope.selected = item;
        };
    }
]);

buildingCtrl.js

app.controller('buildingCtrl', ['$scope', '$routeParams', 
    function ($scope, $routeParams) {         
        console.log($routeParams.buildingName); 
    }
]);

town.html

<div class="row" ng-controller="townCtrl">
    <div class="col-md-3">
        <div class="list-group">
            <a ng-repeat="building in buildingsList" 
               ng-click="select(building)" 
               ng-class="{active: selected === building}"
               class="list-group-item"
               ng-href='#/building/{{building.route}}'>
                {{building.name}}
            </a>
        </div>
    </div>
    <div class="col-md-9">
        <div ng-view></div>
    </div>
</div>

So, when I click on the item Foo the url became ~/#/building/foo, buildingCtrl displays 'foo' in the console and building.html is properly rendered in the page.

But if I reload the page manually (i. e. F5), the URL stays the same, building.html isn't displayed, and worst, if I click on 'Foo' again nothing append...

Could you help me to fix this ? I'm probably missing something on the route.

Upvotes: 0

Views: 58

Answers (1)

Rob
Rob

Reputation: 5481

It looks that you use the townCtrl twice - once for town.html and once for building.html...

Maybe you have to introduce another controller for building or just use the template without one (if you don't need a controller for the building template).

Btw: there is a ui-sref attribute to simplify linking https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref

Upvotes: 1

Related Questions