0

Why bellow code does not work:

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <meta charset="utf-8" />
    <title>Demo</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
    <script>
      angular.module('demo',[])
      .factory('myFactory', function(){
        return {foo: function(){return 'bar';}};
      })
      .run(['myFactory', testFn(myFactory)]);

      function testFn(myFactory){alert(myFactory.foo());}
    </script>
  </head>
  <body ng-app="demo">
  </body>
</html>

But bellow code works:

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <meta charset="utf-8" />
    <title>Demo</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
    <script>
      angular.module('demo',[])
      .factory('myFactory', function(){
        return {foo: function(){return 'bar';}};
      })
      .run(['myFactory', function(myFactory){
        alert(myFactory.foo());
      }]);
    </script>
  </head>
  <body ng-app="demo">
  </body>
</html>

In my application the function to run is lengthy so I don't want to put it inline the app.run because it looks really messy. How to do this?

2 Answers 2

1

Angular's run block requires a pointer to function, so without creating additional function you can rewrite it to something like that:

angular.module('app',[])
      .run(['myFactory', testFn]) // testFn is a pointer to the function.
Sign up to request clarification or add additional context in comments.

4 Comments

may you verify the code? it is short anyway. I don't know how to follow your instruction. I guess you mean .run(['myFactory', testFn]), and it does not work.
Sorry I did not get the meaning "testfn is a pointer to the function. Appreciate if you may change this plnkr to your version to illustrate it.
Sure, plnkr.co/edit/GUUqQrKCtroLoIs4UiVz?p=preview, it a simple optimisation.
Great. Thank you ;)
0

Sorry I'm a idiot. Fixed by this:

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <meta charset="utf-8" />
    <title>Demo</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
    <script>
      angular.module('demo',[])
      .factory('myFactory', function(){
        return {foo: function(){return 'bar';}};
      })
      .run(['myFactory', function(myFactory){
        testFn(myFactory);
      }]);

      function testFn(myFactory) {alert(myFactory.foo());}
    </script>
  </head>
  <body ng-app="demo">
  </body>
</html>

Comments

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.