Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: Controller is called multiple times

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?

like image 844
Vanuan Avatar asked Oct 04 '13 09:10

Vanuan


People also ask

Can we have multiple controllers in AngularJS?

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.

What is an AngularJS controller?

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.

Can we have multiple Ng controller?

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.

Why are controllers used in AngularJS?

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.


2 Answers

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/',
like image 61
Vanuan Avatar answered Sep 20 '22 18:09

Vanuan


This also works if you change to angular version 1.1.5

like image 45
Chandermani Avatar answered Sep 20 '22 18:09

Chandermani