Angular expression to check if model is array or object

后端 未结 2 1000
忘掉有多难
忘掉有多难 2020-12-19 14:55

How can I check if an angular model is an array or an object? Is there a built in or do I have to write a filter isArray with Array.isArray()

{{[] | isA

相关标签:
2条回答
  • 2020-12-19 15:50

    I guess you can also add underscore/lodash to the rootScope and use it:

    _ = require('lodash')
    
    angular.module('app',[])
    .run(function($rootScope){ 
       $rootScope._ = _
    })
    

    And in the template:

    <div ng-show="$root._.isArray(foo)"> 
       <label> First element of Foo </label>
       <span> {{ $root._.first(foo) }} </span>
    </div>
    

    The benefits - you have to add lodash only in one place, and it will be available everywhere. You can use many other things the same way, like Math functions for example. Just be reasonable and don't put too much javascript into expressions.

    0 讨论(0)
  • 2020-12-19 15:54

    You can use the angular.isArray function. It's built-in inside Angularjs.

    If you want to use this function inside your template, you have to create a custom filter: http://docs.angularjs.org/tutorial/step_09

    Example of what you want:

    angular.module('...', []).filter('isArray', function() {
      return function (input) {
        return angular.isArray(input);
      };
    });
    

    Then you can use the filter inside your template:

    {{ myVar | isArray }}
    
    0 讨论(0)
提交回复
热议问题