AngularJs Inline Check if an array check
Asked Answered
C

3

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?

Custody answered 20/8, 2014 at 17:49 Comment(1)
just do ng-show="isArray()" and then in your controller $scope.isArray = function(){ return Array.isArray(textStuff[0][1]) }Walker
L
40

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

$scope.isArray = angular.isArray;

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

Fiddle

Laney answered 20/8, 2014 at 17:56 Comment(0)
S
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>
Smacking answered 20/8, 2014 at 18:2 Comment(1)
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.Robedechambre
U
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>
Underhanded answered 20/8, 2014 at 17:54 Comment(1)
don't store primitives on your scope. scopes inherit but primitives on scopes are copied, not referenced.Robedechambre

© 2022 - 2024 — McMap. All rights reserved.