Angularjs: Controller is called multiple times
26,492
Solution 1
Found an exact same question:
AngularJs: controller is called twice by using $routeProvider
The solution is to add "/" at the end of router url:
- when('/res/:id',
+ when('/res/:id/',
Solution 2
This also works if you change to angular version 1.1.5
Author by
Vanuan
Updated on July 09, 2022Comments
-
Vanuan almost 2 years
For some reason, my controller is double called, when I switch between resource 1 and resource2.
Here's the code:
index.html
<!DOCTYPE html> <html ng-app="multiple_calls"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <link rel="stylesheet" href="style.css" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"> <a href="#res/1">1</a> <a href="#res/2">2</a> <div ng-view> </div> </body> </html>
app.js
var app = angular.module('multiple_calls', []); app. config(['$routeProvider', function($routeProvider) { $routeProvider. when('/res/:id', {templateUrl: 'res.html', controller: 'res' }); }]); app.controller('MainCtrl', function($scope) { }); app.controller('res', function($scope, $routeParams) { console.log('resource called') $scope.id = $routeParams.id; });
res.html
{{id}}
http://plnkr.co/edit/HsCJmbllOcnlvlc1oiHa?p=preview
If you click item 1 and then 2, you'll see that "resource called" is printed 3 times: 2 times for each change between resources.
Any clues why this happens?
-
Simon Arsenault over 6 yearsThis also fixed my problem. However, I'm defining my routes with
$stateProvider
.