When I first used AngularJS I was afraid and always work with high caution because it was like a black box for me with a lot of magic but when I started to know how this magic done it became very friendly framework and started to work with confidence.


I'll share one of the magic features in AngularJS which is Dependency Injection and how it's done behind the scene.


As you see in the controller function $scope parameter that magically filled with AngularJS scope object when you use it.



The magic secret is AngularJS parse the function code as string and parses this string to extract the parameters and check if one of those parameters match a known object like $scope , $location or a user object like user services for example. So know it knows the objects and when it starts to execute the function it pass each object to the location of its argument.


Your question now it possible to convert JavaScript function to string. Yes it's very simple just right function name and .toString()

Ex : myfunc.toString()


Angular have this functions which extract the arguments of a function and return them as array, you can try it yourself.



Now let's dive deep into the code of this function from the angular source code to see what I was taking about.



As you see in the picture it takes  the function as parameter 'fn'

Then in the selected code you can see 'fn.toString()' and in then the other code is just for extracting the parameters from this string and put it in array and return it.


Now it's not magic and just simple idea with some code to achieve.


Comments are closed.