7

It's possible to use typeof in angularjs?

I have an ngrepeat that loop trough my data and should check if data is string or object.

<tr ng-repeat="text in data">
    <td>{{angular.isObject(text) && 'IsObject'||text}}</td>
</tr>

2 Answers 2

7

Please don't use a filter in this case, it's clearly a place for a function in your controller:

<tr ng-repeat="text in data">
    <td>{{isThisAnObject(text)}}</td>
</tr>

And in your controller:

$scope.isThisAnObject = function(input) {
    return angular.isObject(input) ? 'IsObject' : input;
};

It's not only less code, but it also works better in many other places. Filters are for a very specific purpose. Not this!

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

5 Comments

Can you explain why, in this case, a function is better than a filter? What is this "very specific purpose" for filters that makes them a poor choice for this?
yeah please I'd like a better explanation for this @TomBull
A filter, as the name suggests, is designed for filtering. Specifically, filtering arrays - i.e. restricting the items shown in, say, a repeater. It is a (presumably unintended) side-effect that the syntax also works on individual items as in the accepted answer. Although the syntax shown works fine in the simplest case - it quickly gets messy. For example, what happens when you want to compose more than one of these operations? Or process the results of the operation in some other way? Or use the operation in some other context?
Note all of my examples of where a filter breaks down have some (often very convoluted) workaround - but this really is a case of using the most appropriate tool for the job. A function (possibly in a shared library) that is exposed by the controller is the most sensible thing to use in this case.
angular filters are not only for filtering data, but also for formatting data to a sensible string. Some native angular filters work like that. For example, the currency filter: docs.angularjs.org/api/ng/filter/currency
4

Sounds like a good place to use a filter:

<tr ng-repeat="text in data">
    <td>{{text|displayText}}</td>
</tr>
angular.module('myApp').filter('displayText', function() {
    return function(text) {
       return angular.isObject(text) ? 'IsObject' : text;
    };
});

2 Comments

Actually, it's a pretty bad place to use a filter. This is not what filters were intended for and can lead to some seriously poor code if you continue to use the filter elsewhere in a similar way. A better way would be to use a function.
@TomBull why is that bad to use a filter in this case?

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.