Angular zen: directives and scope
¶ by Rob FrieselToday’s moment of Angular zen:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<span data-ngx-my-directive data-my-thing="thing"></span> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var directives = angular.module('app.directives', []); | |
directives.directive('ngxMyDirective', function() { | |
return { | |
scope: { thing: '=myThing' }, | |
link: function(scope, element, attrs) { | |
//scope.thing == attrs.myThings == data-my-thing (on the element) | |
} | |
}; | |
}); |
Try to think of it this way:
Anything that you set on the scope
object in the directive’s return object, those will be the properties pre-populated on the scope
argument passed to the scope
parameter in the function assigned to link
. And those can be inferred from the attributes passed on to the directive’s instance element.
There’s some magic going on there, and it isn’t totally clear from the docs how these things line up. But there’s a science to it.
Leave a Reply