3

I wanted to call a function from $interval's timeout.

angular.module('myApp').factory('myFactory',function($interval){

    var stop;
    return{
        start : function() {
            if(angular.isUndefined(stop)){
                stop = $interval(function() {
                        function1();
                    }
                    ,  30000);
            }
        },

        function1 : function() {
            console.log('In function1');
            function2();
        },

        function2 : function() {
            console.log('In function2');
        }

    }
});

error I am getting is

TypeError: undefined is not a function

Please let me know what could be the reason and how to solve the same

Thanks, ng-R

1 Answer 1

3

My advise it move definition of your functions outside return object please see demo below

var app = angular.module('app', []);
angular.module('app').factory('myFactory', function($interval) {

  function start() {
    $interval(function() {
      function1();
    }, 3000);
  }


  function function1() {
    console.log('In function1');
    function2();
  }

  function function2() {
    console.log('In function2');
  }




  return {
    start: start,
    function1: function1,
    function2: function2
  };
});
app.controller('homeCtrl', function($scope, myFactory) {



  myFactory.start();


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body>
  <div ng-app="app">
    <div ng-controller="homeCtrl">


    </div>
  </div>
</body>

Sign up to request clarification or add additional context in comments.

1 Comment

can you please explain why do we need to move definition of your functions outside return object? what would be the problem if we keep it in return object? @sylwester

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.