Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

People also ask

What is the responsibility of the controller in AngularJS?

The primary responsibility of an AngularJS Controller is to control the data that gets passed to the view. There is two-way communication between the scope and the view .

Can we have multiple controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application. This approach will make your code cleaner and easy to maintain and upgrade. Angular creates one $scope object for each controller.

What is difference between controller and directive AngularJS?

A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.

Can we inject one controller into another controller in AngularJS?

You can't inject controllers into one another.


If you don't have to use URLs like #/item/{{item.id}}/foo and #/item/{{item.id}}/bar but #/item/{{item.id}}/?foo and #/item/{{item.id}}/?bar instead, you can set up your route for /item/{{item.id}}/ to have reloadOnSearch set to false (https://docs.angularjs.org/api/ngRoute/provider/$routeProvider). That tells AngularJS to not reload the view if the search part of the url changes.


If you need to change the path, add this after your .config in your app file. Then you can do $location.path('/sampleurl', false); to prevent reloading

app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
    var original = $location.path;
    $location.path = function (path, reload) {
        if (reload === false) {
            var lastRoute = $route.current;
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                $route.current = lastRoute;
                un();
            });
        }
        return original.apply($location, [path]);
    };
}])

Credit goes to https://www.consolelog.io/angularjs-change-path-without-reloading for the most elegant solution I've found.


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.


For those who need path() change without controllers reload - Here is plugin: https://github.com/anglibs/angular-location-update

Usage:

$location.update_path('/notes/1');

Based on https://stackoverflow.com/a/24102139/1751321

P.S. This solution https://stackoverflow.com/a/24102139/1751321 contains bug after path(, false) called - it will break browser navigation back/forward until path(, true) called