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?

1
  • just do ng-show="isArray()" and then in your controller $scope.isArray = function(){ return Array.isArray(textStuff[0][1]) } Commented Aug 20, 2014 at 17:54

3 Answers 3

40

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

$scope.isArray = angular.isArray;

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

Fiddle

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

Comments

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>

1 Comment

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.
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>

1 Comment

don't store primitives on your scope. scopes inherit but primitives on scopes are copied, not referenced.

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.