8

In angular directives I've seen in tutorials either

 link: function($scope,$element,attrs)

or

 link: function(scope,element,attrs)

Now I know that the '$' means a service in angular , does this hold here ? What exactly is the difference between $scope and scope ? Same goes to element vs $element

4
  • 2
    $ does not mean service in Angular. It denotes some Angular property so it would not collide with your model's properties. It is a simple as it gets - a prefix, nothing more. You can use either approach. Commented Sep 10, 2013 at 12:40
  • what do u mean , for example isn't $http a service ? if u hold off the '$' in $http I don't think the service will be injected Commented Sep 10, 2013 at 12:51
  • $injector resolves dependencies in 3 ways: inline annotations, $inject annotations and inferred arguments. Therefore in some cases it will work without the $. You can read it in Angular's manual. While $http is a service, neither $scope, nor $attributes aren't. They denote Angular properties (services including). Commented Sep 10, 2013 at 13:16
  • If you're new to Angular, just stick with the $. Once you get comfortable with the $injector, you can choose you own approach. But keep in mind that with such convetion any code minification script will break you dependencies. Commented Sep 10, 2013 at 13:20

1 Answer 1

13

In your specific example, it does not matter what the parameters are named in your link function. When Angular processes the directive, it will pass the scope, element and attrs (and even a controller instance if configured) to your link function.

You could do this (not recommended):

link: function (s, e, a)

and it will work fine.

$ is the prefix used by Angular. It is a convention and helps avoid naming collisions.

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

4 Comments

It should be noted that this is different than a controller (for example): the controller uses injection, so it parses the parameters to be passed from the parameter names (or optionally, previous elements in the array), while this is simply an old-school function with fixed parameters.
Thanks Joachim that's what confused me , I was thinking it behaves like a controller
As noted by Joachim Sauer, in a controller parameters are dependency injected, so $scope is a valid service, and scope is not. Using $scope with the dollar sign in link functions is not needed, but many people do it, perhaps to keep the same naming conventions everywhere in the code.
This and many more issues are precisely explained at www.egghead.io i recommend that as a very good extension of the actual API

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.