Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs using instanceof in expression

Tags:

angularjs

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>
like image 334
Tropicalista Avatar asked Sep 23 '13 21:09

Tropicalista


2 Answers

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!

like image 200
Tom Bull Avatar answered Oct 25 '22 18:10

Tom Bull


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;
    };
});
like image 43
urish Avatar answered Oct 25 '22 16:10

urish