I'm using an Angular element directive to generate an amount of stars (rating) for a given item.
I create a directive called 'generateStars' and I am using it like so in the view.
<generate-stars amount="3"></generate-stars>
I don't want the directive to be dependant on the current scope so I was wondering if I could take in the "amount" attribute and get the value within my directive function.
Here is that function:
angular.module('myapp.directives', [])
.directive('generateStars', function() {
var html = '<i class="fa fa-star"></i>';
return {
restrict: 'E',
template: html,
replace: true
};
});
I couldn't find any obvious documentation to allow me to get the value of 'amount' inside my directive function.
Any help would be much appreciated. Thanks.
You could use isolated scope and use amount value can be passed as attribute as you are doing so.
Markup
<generate-stars amount="{{amount}}"></generate-stars>
Controller
$scope.amount = 3; //passing it through the scope.
Directive
angular.module('myapp.directives', [])
.directive('generateStars', function() {
var html = '<i ng-repeat="i in [1, 2, 3, 4, 5]" class="fa fa-star" ng-if="i>=amount"></i>';
return {
restrict: 'E',
template: html,
replace: true,
scope: {
amount: '@' //`@` for one way binding.
}
};
});
This can be without isolated scope. Basically you need to create class fa-3x in your directive template.
angular.module('myapp.directives', [])
.directive('generateStars', function() {
return '<i ng-repeat="i in [1, 2, 3, 4, 5]" class="fa fa-star" ng-if="i>='+ attrs.amount +' "></i>'
};
return {
restrict: 'E',
template: html,
replace: true
};
});
You can use attrs object available in your link function of your Directive Definition Object.
angular.module('myapp.directives', [])
.directive('generateStars', function() {
var html = '<i class="fa fa-star"></i>';
return {
restrict: 'E',
template: html,
replace: true,
link: function(scope, element, attrs) {
/*all attributes passed to directive are available as properties
on attrs object*/
console.log(attrs.amount);
}
};
});
HTML
<generate-stars amount="3"></generate-stars>
With that, when your directive is rendered, prints the value 3 in console.
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