dc7a9163d9 dc7a9163d9 - 5 months ago 15
AngularJS Question

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?

Answer

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