ca9163d9
ca9163d9

Reputation: 29159

Why the code in controller are called twice?

There is the following code in the html file templates\events.html.

<div class="events-2colmn-l backgnd-cover" ui-sref="menu.music">
    MUSIC
</div>

In route.js

  .state('menu.music', {
    url: '/music',
    views: {
      'side-menu21': {
        templateUrl: 'templates/music.html',
        controller: 'musicCtrl'
      }
    }
  })

And in the controller there is

.controller('musicCtrl', function ($scope, EventService) { // called twice when clicked
    var allEvents = EventService.query({ category: "Music" });
    allEvents.$promise.then(function (response) { 
        $scope.events = response;  
    });
})

The code in the controller is always called twice when the <div ...>MUSIC</div> is touched. How to make sure it's only called once when clicked?

Upvotes: 2

Views: 89

Answers (2)

Pankaj Kumar
Pankaj Kumar

Reputation: 881

It is because your controller is being called twice...

  • Once when you are calling

  • And the second time when the templates/music.html is called because you must be using ng-controller directive in music.html as well...kindly check

Upvotes: 3

Srijith
Srijith

Reputation: 1444

You should have the controller associated with the html either through the ng-controller or in your states in app.js.

So when you have your state like this

.state('menu.music', {
 url: '/music',
 views: {
  'side-menu21': {
    templateUrl: 'templates/music.html',
    controller: 'musicCtrl'
   }
  }
})

you dont need the ng-controller in your music.html. Thats what is causing the controller being called twice. Try removing the ng-controller and verify

Upvotes: 2

Related Questions