AngularJs Inline Check if an array check

后端 未结 3 1722
庸人自扰
庸人自扰 2020-12-17 10:45

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

I would have thought this to work:

相关标签:
3条回答
  • 2020-12-17 11:04

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

    $scope.isArray = angular.isArray;
    

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

    Fiddle

    0 讨论(0)
  • 2020-12-17 11:04

    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>
    
    0 讨论(0)
  • 2020-12-17 11:10

    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>
    
    0 讨论(0)
提交回复
热议问题