3

I am in angularjs. I am trying to append paramter in url using $location.search('sid', key);. The value of key is coming from another server by http request. Here is the code for append parameter.

.config(['$routeProvider',function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'test1.html',
                controller: 'test1Controller'
            })
            .when('/message/:userId', {
                templateUrl: 'test2.html',
                controller: 'test2Controller'
            })
            .otherwise({
                redirectTo: '/'
            });
    }])
.run(['$route', '$rootScope', '$location' ,'getAuthDetails', function($route, $rootScope, $location,getAuthDetails) {
        var key;

        getAuthDetails.get().then(function(data){
            key = data.key;
            $rootScope.query = 'sid='+key;
            console.log($location.$$path);
            $location.search('sid', key);  //append parameter. This is calling controller twice
        });

        $rootScope.$on('$routeChangeSuccess', function () {
            $rootScope.query = 'sid='+key;
        });
    }]);

The problem i am having is . As the sid get append in url. The console.log i put in test1Controller getting called twice. Sid is used to connect with socket connection.

Is there any workaround to call the controller after the url append.

NeiL
  • 791
  • 8
  • 35

2 Answers2

6

You can use reloadOnSearch: false

Example:

.config(['$routeProvider',function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'test1.html',
                controller: 'test1Controller',
                reloadOnSearch: false // wont reload the controller when the search query changes
            })
            .when('/message/:userId', {
                templateUrl: 'test2.html',
                controller: 'test2Controller'
            })
            .otherwise({
                redirectTo: '/'
            });
    }])
Kushal
  • 1,360
  • 6
  • 16
  • @Neil There are lots of small features that are hidden in angular that even the angular docs dont provide it with explanation. – Kushal Apr 22 '15 at 12:12
1

Make sure you are writing controller only once. write either in ng-controller or in your config route:

app.config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/',
        { 
            templateUrl: 'pages/home.html'
            //Remove controller from here
        });
    }]);

home.html

<!-- Add the ng-controller in your view -->
<div ng-controller="MyItemsController">
    <!-- Your stuff -->
</div>

Try using reloadOnSearch: false inside your config it will prevent controller from loading.

LeftyX
  • 35,328
  • 21
  • 132
  • 193
dev
  • 313
  • 2
  • 9