AngularJS : How to not render an attribute if value is undefined

707 Views Asked by At

I have a template used in a directive, looking like :

<tr>
    <th ng-repeat="col in tableSpec" st-sort="{{col.sortField}}"></th>
</tr>

The attribute st-sort should not be render (no attribute at all) when the col.sortField doesn't exists.

I've read about the 'allOrNothing' option in the $interpolate witch does what I want but I don't if it is possible to specify this option when using the {{ }} notation.

I've read also about the ngAttr and I try to use this notation ng-attr-st_sort="{{col.sortField}}" but without success anymore.

Any healp would be greatly appreciated.

Jean-Marc

1

There are 1 best solutions below

3
On

As I understand, your directive stSort has a template. You can add ngHide directive to you template root element, and $observer condition if col.sortField exists or not?

.directive('stSort', [function () {
    return {
        restrict: 'EA',
        template: '<div ng-hide="$notRender"></div>',
        link: function(scope, element, attrs) {
            attrs.$observe('stSort', function(newVal, OldVal){
                 if(!newVal)
                     scope.$notRender = true
                 else
                    scope.$notRender = false;

                 //do your staff

            })
        }
    };
}])