18

Inline in AngularJs is there a way to check if something is an array?

I would have thought this to work:

<div ng-show="Array.isArray(textStuff[0][1])">Hi</div>

I have verified it is in fact an array. Is there something I am missing or another way?

Adam
  • 3,301
  • 6
  • 28
  • 50
  • just do `ng-show="isArray()"` and then in your controller `$scope.isArray = function(){ return Array.isArray(textStuff[0][1]) }` – Ronnie Aug 20 '14 at 17:54

3 Answers3

40

You can put angular.isArray on the scope...

$scope.isArray = angular.isArray;

<div ng-show="isArray(textStuff[0][1])">Hi</div>

Fiddle

Anthony Chu
  • 35,726
  • 9
  • 77
  • 66
6

You can create global filters to use in your JS or HTML to check against object types. This way you don't pollute your $rootScope or $scopes to use it everywhere, unlike the accepted answer... Angular also has some built in utility functions that can check object types:

angular
    .module("yourModule")
    .filter("isArray", function() {
        return function(input) {
            return angular.isArray(input);
        };
    });

In HTML:

<div ng-show="{{ textStuff[0][1]) | isArray }}">Hi</div>

You may also inject the $filter service into your Controller to access the custom filter by name and compute the filtered results when your controller instance is instantiated (and also when your data changes). This prevents performance issues due to the view expression getting computed rapidly.

angular
    .module("yourModule")
    .controller("MyController", MyController);

MyController.$inject = ["$filter", "$scope"];

function MyController($filter, $scope) {

    this.testStuff = []; // your data
    this.filteredResult = $filter("isArray")(this.testStuff[0][1]);

    // or if you need to watch for data changes
    var vm = this;

    $scope.$watchCollection(
        function() { return vm.testStuff },
        function(newTestStuff) {  
            vm.filteredResult = $filter("isArray")(newTestStuff[0][1]);
        } 
    );
}

<div ng-controller="MyController as my">
    <div ng-show="my.filterResult">Hi</div>
</div>
SirTophamHatt
  • 1,591
  • 17
  • 23
  • this is a much better (and clever) solution. unlike the function-on-scope answer, this is actually testable since you can inject your own, named filter. – icfantv Aug 21 '15 at 20:17
1

I would separate logic from the view. Add state in scope and then check it

 $scope.showHi = angular.isArray(textStuff[0][1]);

In view

<div ng-show="showHi">Hi</div>
Lukasz Madon
  • 13,748
  • 13
  • 58
  • 93
  • 2
    don't store primitives on your scope. scopes inherit but primitives on scopes are copied, not referenced. – icfantv Aug 21 '15 at 20:16