0

I have an Angular controller and I have some setup code that I only want to be triggered once. So I placed the code inside the controller. But for some reason I can see the code being executed multiple times.

.controller('MyController', function ($rootScope, $scope, $compile, $http, $filter, $q, MyService) {

    alert('should be fired only once!');

I think the culprit is in the closeTimes function which basically hides the time html control after a timer.

  $scope.closeTimes = function() {
        // create a promise to fire a function when this animation finishes
        var deferred = $q.defer();
        var element = document.querySelector(".time-box");
        var innerElement = document.querySelector(".inner");

        // animate the box closed
        move(element)
          .ease('ease-out-cubic') //used by animate.css
          .set('height', '0px')
          .duration('.25s')
          .end();
        move(innerElement)
          .ease('ease-out-cubic')
          .set('height', '0px')
          .duration('.25s')
          .end(function () {

            element.remove();
            deferred.resolve();

          });
          // return promise
          return deferred.promise;
      };

The closeTimes uses the promises as follows:

 $scope.closeTimes().then(function() {
                //  // now show the new selected date
                  $scope.openTimes(selectedSlot);
                });

For some reason when I call the closeTimes function it automatically calls the alert('should be fired only once!'); code. Why is it initializing the code again.

john doe
  • 9,220
  • 23
  • 91
  • 167
  • Are you using routing? Perhaps you have listed in your route as well as in the page itself? I have seen that cause the controller to fire twice. Similar to this post: http://stackoverflow.com/a/26157303/426422 – Mike Cheel Mar 14 '16 at 19:10
  • Nope I am using Angular in ASP.NET MVC application. I believe for some reason the promises is being handled by controller initialization code even though that has nothing to do with controller. The openTimes, closeTimes is firing the promises which for some reason causes the controller to initialize again. – john doe Mar 14 '16 at 19:14

0 Answers0