6

I have one concern when creating a custom directive in angular. When I'm using a link function, I'm not sure what is the real difference when accessing attributes with attrs or scope. Take this piece of code for example:

myApp.directive('someDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            title: '=title'
        },
        template: '<img/>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                // do something here
            }
            if (attrs.title){
                // do something here
            }
        },
    }

From my observations accessing 'title' attribute from attrs and by scope has a similar effect. What is the real difference?

Shawn J. Molloy
  • 2,457
  • 5
  • 41
  • 59
Marcin86
  • 131
  • 2
  • 9
  • Please look at this http://stackoverflow.com/questions/14300986/angularjs-directive-isolated-scope-and-attrs – michelem Jun 22 '15 at 19:53

1 Answers1

20

The difference is that attribute is of a String type by definition. Always. In your case attrs.title will be literally string equal to whatever you pass into attribute in HTML.

However, scope.title is parsed and evaluated result of the attribute attr.title.

Ex. If you use something like this in HTML

<some-directive title="name"></some-directive>

where $scope.name = "Thomas Mann" defined in the scope, then attr.title will be string "name", while scope.title will be "Thomas Mann".

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Awesome answer. To add to that, you can also do `scope.$eval(attrs.title)` to get a parsed version of the attribute within the context of the scope. – Josh Beam Jun 22 '15 at 19:57
  • That's all? I think when you use @ for binding scope it is also being passed as string so it has same effect, right? – Marcin86 Jun 22 '15 at 19:57
  • 1
    @Marcin86, pretty much something passed into an attribute is a string, and something passed as a scope variable can be whatever data type. But you can also do `scope.$eval(attrs.title)` to evaluate the attribute in the context of the scope, as I commented above. – Josh Beam Jun 22 '15 at 19:58