Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs controller executes twice

Tags:

angularjs

A similar question was asked here but it did not help me.

I am learning angularjs and I noticed the controller is executed twice.

I have a very simple fiddle example that shows the behavior here

I built the example as I was learning about services and at first I thought it was the injecting of the services into the controller but I commented all the code related to the services and still the controller is executed twice.

My example works but I am afraid I am doing something wrong.

<div ng-app="MyApp">
  <div ng-controller="MyCtrl">
    {{data1}} 
  </div>
</div>

var app = angular.module('MyApp', [])
app.service('Service1', function(){
  return {
    ajxResponse1: 'dataFromService1'
  };
 });

function MyCtrl($scope, Service1){
  alert('Entering MyCtrl');
  $scope.data1 = Service1.ajxResponse1;    
  alert('Exiting MyCtrl');
}
like image 780
user2223142 Avatar asked Nov 28 '22 09:11

user2223142


2 Answers

One possible source is this: if you are using Routing and specify the controller in routes - you must not specify it in template that the route uses. We had that problem when this was overlooked.

like image 146
Ivan Koshelev Avatar answered Dec 23 '22 22:12

Ivan Koshelev


Your controller was running twice in the fiddle because angular is referenced twice (once via the Frameworks & Extensions drop down and another as an External Resource).

See this updated fiddle where I removed the External Resource and the alerts only show up once.

The code remains unchanged:

function MyCtrl($scope, Service1, Service2, Service3){
    alert('Entering MyCtrl');
    $scope.data1 = Service1.ajxResponse1;
    $scope.data2 = Service2.ajxResponse2;
    $scope.data3 = Service3.ajxResponse3;
    alert('Exiting MyCtrl');
}
like image 27
Gloopy Avatar answered Dec 23 '22 22:12

Gloopy