Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom directive scope vs attrs

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?

like image 235
Marcin86 Avatar asked Jun 22 '15 19:06

Marcin86


1 Answers

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".

like image 148
dfsq Avatar answered Sep 24 '22 16:09

dfsq