0

I have a class called late that I'd like to apply conditionally:

<div ng-class="late: isLate"></div>

I have a directive called isLate that performs a calculation and returns a boolean. What is the right way to link these two? I searched the directive documentation and didn't find anything that does this. Maybe using directives isn't the right way to do this?

2 Answers 2

3

At first move your calculation from directive to scope:

$scope.isLate = function() {
  // make calculations here and return bool value 
}

And then pass object to ng-class directive:

<div ng-class="{late: isLate()}"></div>  

For each key-value pair of the object with a truthy value the corresponding key is used as a class name. (from ngClass docs)

Sign up to request clarification or add additional context in comments.

1 Comment

This works. My impression was the directives are better than $scope.function() but this works.
0

For ng-class you need to provide an object that is used as a map with the class name mapped to some expression that evaluates to a boolean condition. (other use cases exist but this is closest to what you're showing).

http://docs.angularjs.org/api/ng/directive/ngClass

so something like this would work assuming that isLate was a boolean on your controller scope

<div ng-class="{'late':isLate}"></div>

I don't know that a directive is the right approach here since they are generally used for adding behavior and DOM manipulation. Or rather I don't think that using a directive within the ng-class is the right approach, though perhaps just having a custom directive that you use as an attribute on the DOM element could work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.