Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a directive use filtered HTML attributes?

I have a directive that builds a popup menu which automatically collects data from HTML. It is actually supposed to convert a set of Bootstrap carousel-compliant elements, into a list. A catch is that each .item carries an attribute with its string value filtered, as in:

HTML:

<div class="item" data-title="{{'My string' | myfilter}}">
   ...
</div>

When I link the directive to element, using this snippet:

.directive('sectionBuilder', function(){
    return {
        priority:100,
        restrict: 'C',
        link: function(scope, element, attrs){
            var data = [];
            $('.carousel-inner > .item', '#carousel').each(function(i, el){
                data.push({k: i, v: $(el).attr('data-title')})
            });
        }
    }
})

I get a menu of raw, unprocessed strings used in HTML:

{{'My string' | myfilter}}
{{'My string 2' | myfilter}}

From what I understand, attrs.$observe applies to attributes of the element being bound to directive, but not the external elements.

How do I get angular to use the filtered strings? I tried setting priority to a extreme values, but to no avail.

like image 469
user776686 Avatar asked Nov 09 '22 14:11

user776686


1 Answers

You could use ng-attr, that would be more convenient solution. ng-attr-data-title will evaluate interpolation {{}} & create data-title attribute with value.

Instead of using data-title="{{'My string' | myfilter}}" use ng-attr-data-title="{{'My string' | myfilter}}"

Markup

<div class="item" ng-attr-data-title="{{'My string' | myfilter}}">
   ...
</div>

Update

As you are getting value like {{'My string' | myfilter}}, {{'My string 2' | myfilter}} with interpolation then you could use $parse or $interpolate service to evaluate them.

.directive('sectionBuilder', function($interpolate){
    return {
        priority:100,
        restrict: 'C',
        link: function(scope, element, attrs){
            var data = [];
            $('.carousel-inner > .item', '#carousel').each(function(i, el){
                data.push({k: i, v: $interpolate($(el).attr('data-title'))})
            });
        }
    }
})
like image 171
Pankaj Parkar Avatar answered Nov 15 '22 06:11

Pankaj Parkar