Search code examples
angularjsangularjs-ng-route

How to redirect views using the same angularjs controller?


When i am using "location.href" in order to redirect to another view my current controller reinitialize. The both views are using the same controller. What is the better way to go between views but not recreating controller?

   function onAddNewTest() {
            //some logic here
            location.href = '/#/testList';
    };

route itself:

    .module('applicationModule', ['ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider
        .when('/testList', {
            controller: 'testController as vm',
            templateUrl: '/Scripts/views/testList.html'
        })

Solution

  • Try to use $location.path() in your controller like this:

    function onAddNewTest() {
        //some logic here
        $location.path('/testList');
    };
    

    And don't forget to add dependency to your controller.

    Hope it helps