Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular element directive how to get attribute value

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.

like image 240
Dan Avatar asked Mar 02 '26 23:03

Dan


2 Answers

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
    };
});
like image 74
Pankaj Parkar Avatar answered Mar 05 '26 13:03

Pankaj Parkar


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.

like image 40
Arkantos Avatar answered Mar 05 '26 11:03

Arkantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!