Custom Scope vs attrs

I have one problem when creating a custom directive in angular. When I use the link function, I'm not sure if this 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, a similar effect has access to the 'title' attribute from attrs and in volume. Who cares?

+6
source share
1 answer

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

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

Ex. If you use something like this in HTML

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

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

+19
source

Source: https://habr.com/ru/post/989551/


All Articles