Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Can you change a path without reloading the controller in AngularJS?

It's been asked before, and from the answers it doesn't look good. I'd like to ask with this sample code in consideration...

My app loads the current item in the service that provides it. There are several controllers that manipulate the item data without the item being reloaded.

My controllers will reload the item if it's not set yet, otherwise, it will use the currently loaded item from the service, between controllers.

Problem: I would like to use different paths for each controller without reloading Item.html.

1) Is that possible?

2) If that is not possible, is there a better approach to having a path per controller vs what I came up with here?

var app = angular.module('myModule', []).
config(['$routeProvider', function($routeProvider) {
when('/items', {templateUrl: 'partials/items.html', controller: ItemsCtrl}).
when('/items/:itemId/foo', {templateUrl: 'partials/item.html', controller: ItemFooCtrl}).
when('/items/:itemId/bar', {templateUrl: 'partials/item.html', controller: ItemBarCtrl}).
otherwise({redirectTo: '/items'});

<!-- Menu -->
<a id="fooTab" my-active-directive="" href="#/item/{{}}/foo">Foo</a>
<a id="barTab" my-active-directive="" href="#/item/{{}}/bar">Bar</a>
<!-- Content -->
<div class="content" ng-include="" src="view.template"></div>

// Helper function to load $scope.item if refresh or directly linked
function itemCtrlInit($scope, $routeParams, MyService) {
$scope.item = MyService.currentItem;
if (!$scope.item) {
MyService.currentItem = MyService.get({itemId: $routeParams.itemId});
$scope.item = MyService.currentItem;
function itemFooCtrl($scope, $routeParams, MyService) {
$scope.view = {name: 'foo', template: 'partials/itemFoo.html'};
itemCtrlInit($scope, $routeParams, MyService);
function itemBarCtrl($scope, $routeParams, MyService) {
$scope.view = {name: 'bar', template: 'partials/itemBar.html'};
itemCtrlInit($scope, $routeParams, MyService);

1 Answer

why not just put the ng-controller one level higher,
<body ng-controller="ProjectController">
<div ng-view><div>

And don't set controller in the route,
.when('/', { templateUrl: "abc.html" })

it works for me.

Login / Signup to Answer the Question.