问题
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.
回答1:
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: '/'
});
}])
回答2:
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.
来源:https://stackoverflow.com/questions/29796557/controller-getting-called-twice-due-to-append-params-in-url