0

Suppose my model has some info field and this info could have a "prop" property.

I am rendering a div and would like it to have an attribute with the value of that property.

This is simple enough using <div attr="{{info.prop}}"></div>.

But if info does not have the prop or has it with a null value it renders <div attr></div>

How can I prevent attr from being added to the div?

And in a more general way how can I examine the model and add the attribute only if some conditions apply?

I suppose I could have the model include a special function in the scope and use <div {{attrGetter()}}"></div> or <div {{attrGetter(info.prop)}}"></div> and have this logic in the controller. But I wanted to know if there are better/other ways to do this.

1 Answer 1

1

This is where I would use a directive, where-in the link function you have access to the elements attributes:

.directive("myDirective", function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            if (scope.info.hasOwnProperty("prop"))
                attrs["attr"] = scope.info.prop
        }
    }
});

And throw this directive onto your target element:

<div my-directive></div>
Sign up to request clarification or add additional context in comments.

2 Comments

directive would be the best way to do it if you are really trying to avoid rendering the extra markup
Thanks, what if I have prop1 and prop2 ? would you add another if to the same directive? or is there a more general way to do this? maybe an element directive "<add-attr if="info.hasOwnProperty('prop')" attr="myAttr" value="info.prop"> and have it modify the parent element... maybe I will go that way...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.