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?
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.
The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.
We can create multiple controller in Angular JS Application. Almost all project have the requirement to use multiple controller in Angular JS. Each controller have different responsibility and functions depends upon our requirements.
AngularJS controllers are used to control the flow of data of AngularJS application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions.
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/',
This also works if you change to angular version 1.1.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With