4

How can I check if an angular model is an array or an object? Is there a built in or do I have to write a filter isArray with Array.isArray()

{{[] | isArray}} doesn't work

  • 3
    google ? http://docs.angularjs.org/api/ng/function/angular.isArray – steo Mar 12 '14 at 15:43
  • wah. didn't find it. thanks! –  Mar 12 '14 at 15:45
  • this doesn't work in an expression –  Mar 12 '14 at 15:53
  • `angular.isArray` can be used only in javascript code. Tell us why you need to check and how you will use it. – Ye Liu Mar 12 '14 at 15:56
  • BTW there is a very interesting page where you can find lots of useful stuff... it's called angular API docs http://docs.angularjs.org/api – doodeec Mar 12 '14 at 15:56
  • No need to be rude. I want to check if an object is an array in an expression. Currently I'm using an simple filter and wondered if there is a built in for it (https://gist.github.com/mren/12cd33637e9c54641acc). –  Mar 12 '14 at 15:59
  • 2
    `scope.isArray = angular.isArray` – doodeec Mar 12 '14 at 16:03

2 Answers2

11

You can use the angular.isArray function. It's built-in inside Angularjs.

If you want to use this function inside your template, you have to create a custom filter: http://docs.angularjs.org/tutorial/step_09

Example of what you want:

angular.module('...', []).filter('isArray', function() {
  return function (input) {
    return angular.isArray(input);
  };
});

Then you can use the filter inside your template:

{{ myVar | isArray }}
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
  • thanks. You're right, this is working. Do you know if there is a built in to check for this or do I need to roll my own filter? This looks like a basic check –  Mar 12 '14 at 16:01
  • The filter does not exist in Angular. You have to code it. If your problem is solved, don't forget to accept the answer ;) – Sandro Munda Mar 12 '14 at 16:23
1

I guess you can also add underscore/lodash to the rootScope and use it:

_ = require('lodash')

angular.module('app',[])
.run(function($rootScope){ 
   $rootScope._ = _
})

And in the template:

<div ng-show="$root._.isArray(foo)"> 
   <label> First element of Foo </label>
   <span> {{ $root._.first(foo) }} </span>
</div>

The benefits - you have to add lodash only in one place, and it will be available everywhere. You can use many other things the same way, like Math functions for example. Just be reasonable and don't put too much javascript into expressions.

iLemming
  • 34,477
  • 60
  • 195
  • 309