AngularJs Inline Check if an array check

点点圈 提交于 2019-11-29 05:37:54

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

$scope.isArray = angular.isArray;

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

Fiddle

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>

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!