Please see the example here
foodMeApp.directive('fmRating', function() { return { restrict: 'E', scope: { symbol: '@', max: '@', readonly: '@' }, require: 'ngModel', link: function(scope, element, attrs, ngModel) { attrs.max = scope.max = parseInt(scope.max || 5, 10); ... Angular needs symbol , max, readonly to be defined in the isolated scope object to access it from parent scope.
it is used here
<fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"></fm-rating>
So, what is the purpose of attrs? Can't one access all the attributes passed through attrs. Why can't one access value of max as attrs.max instead of scope.max
Why assign back like attrs.max = scope.max ?
Since this app is written by Angular authors, I expect a reason.
thanks.
Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.
Using attrs you are able to access the attributes defined in your html tag like <fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"> So in this case you will have access to the symbol and readonly attributes.
These prefixes are used to bind the parent scope's methods and properties to the directive scope. There are 3 types of prefixes in AngularJS: '@' – Text binding / one-way binding. '=' – Direct model binding / two-way binding.
what is the purpose of attrs?
Attributes defined on the same element as your directive have a few purposes:
Can't one access all the attributes passed through attrs?
Yes you can, but
{{}}s will cause you problems, since they will not be interpolated. <my-directive name="My name is {{name}}"> and the parent scope has $scope.name='Mark'. Then, inside the linking function, console.log(attrs.name) results in undefined. attrs.$observe('name', function(val) { console.log(val) }) results in My name is Mark. (Note that inside the linking function, $observe() must be used to get the interpolated value.)Why can't one access value of max as attrs.max instead of scope.max
answered above
Why assign back like attrs.max = scope.max ?
The only reason I can think of for doing this is in case some other directive needs to see this attribute/value (i.e., inter-directive communication). However, the other directive would need to run after this directive for this to work (which can be controlled somewhat with the priority directive setting).
Summary: in a directive with an isolate scope, normally you don't want to use attrs. (I suppose it could be a way to send initialization data/values into a directive -- i.e., if you don't need databinding for these values and you don't need interpolation.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With