0

I am using ngRoute. index.html :

    <body  ng-app="mainApp" ng-controller="AboutController">    
    <div id="header">
    <h1>Employee Gallery</h1>
    </div>
<div id="leftpanel">
    <!--a href="#/displayEmp" id="load">Display</a><br-->
    <a href="#/display">Display</a><br>    
    Insert<br>
    Delete
</div>

<!-- Angular dynamic content-->
<div   ng-view id="section">      
</div>

main.js :

var app = angular.module('mainApp',['ngRoute']);
app.config(function($routeProvider) {
    $routeProvider
        .when('/display', {
            templateUrl: 'pages/display.html',
            controller: 'DisplayController'
        })
        .when('/', {
            templateUrl: 'pages/about.html',
            controller: 'AboutController'
        });
        /*.otherwise({
            redirectTo: '/'
        });*/
});
app.controller('AboutController', function($scope) {
    console.log("In AboutController");
    $scope.msg = "This app performs CRUD operations";
});

If ng-app="mainApp" is specified in the body tag of index.html as shown, 'In AboutController' is printed twice. If ng-app="mainApp" is moved to then it is printed once, as should be. In both cases, output is the same. 1) But need to understand why the controller is executed twice in one case and once in the other. 2) In display.html, console.log is not getting printed within tag.

kakoli
  • 423
  • 4
  • 8
  • 18

1 Answers1

0

You're running the ctrl code twice. Once in the <body> tag and another in the route definition. You don't need to define ng-controller="AboutController" in <body>, the router is going to do that for you in your template html, which is templateUrl: 'pages/about.html' for that route.

When using the router you don't need to explicitly set an ng-controller directive on an html element like you have above, the router declares it for you.

<body ng-app="mainApp">    
    <div id="header">
        <h1>Employee Gallery</h1>
    </div>
    <div id="leftpanel">
        <!--a href="#/displayEmp" id="load">Display</a><br-->
        <a href="#/display">Display</a><br>    
        Insert<br>
        Delete
    </div>

    <!-- Angular dynamic content-->
    <div ng-view id="section"></div>
</body>

Further reading: Combating AngularJS executing controller twice

Community
  • 1
  • 1
Pathsofdesign
  • 4,678
  • 5
  • 18
  • 26
  • The point that you all have pointed about ng-controller is right. But my question is more on shifting ng-app from body tag to div tag.The controller is executed twice only if ng-app is specified in the body tag of index.html as shown above. If ng-app is moved to
    tag(with ng-controller still in the body) as shown below, then controller is executed once only. Like this : ............. .
    – kakoli Jan 03 '16 at 05:48