Ng-repeat for object without array

I know ng-repeat only works on an array.

My problem is that I don't know if the object I am receiving from the server is an array or just an object.
I need to define dynamically if it is an array or an object, and only if it uses ng-repeat.

My question is, what is the best way to implement using ng-repeat with a condition - only if the object is an array?

I tried to solve the problem like this:

 <div ng-if="Array.isArray(myObj)"ng-repeat="item in myObj">
      <do-some-stuff item='item'></do-some-stuff>
 </div>
 <do-some-stuff ng-if="!Array.isArray(myObj)" item='myObj'></do-some-stuff>

      

But it doesn't work.

+3


source to share


3 answers


ng-repeat priority is 1000 and ng is if the priority is 600 so that ng-repeat executes first and then ng-if. so your code doesn't work. Use this code:



<div ng-if="Array.isArray(myObj)">
      <div ng-repeat="item in myObj">
          <do-some-stuff item='item'></do-some-stuff>
      </div>
 </div>
 <do-some-stuff ng-if="!Array.isArray(myObj)" item='myObj'></do-some-stuff>

      

+6


source


Directive precedence can be a problem, but I would say the reason is different.

Angular is trying to find the definition of Array.isArray () on the current $ scope. And can't find it.

You have to add a reference to $ window to your controller and then declare your own function to check if the object is an array.

something like that



Controller:

 $scope.isArray = function(obj) { 
  //Check if Array.isArray is available (is not supported in IE8)
  var fn = $window.Array.isArray || $window.angular.isArray;
  return fn(obj);
 }

      

Html

<div ng-if="isArray(myObj)">
      <div ng-repeat="item in myObj">
          <do-some-stuff item='item'></do-some-stuff>
      </div>
 </div>
 <do-some-stuff ng-if="!isArray(myObj)" item='myObj'></do-some-stuff>

      

0


source


This can be achieved in another way.

you can return the required array or empty value based on your conditions using the testForArray function

<div  ng-repeat="item in testForArray()">
      <span>{{item.name}}</span>
      <do-some-stuff item='item'></do-some-stuff>
 </div>

      

Within this function, you can check your required logic whether the data is an array or an object

var myObj = [{name : '1'},{name : '3'},{name : '3'}]


      $scope.testForArray = function(){
        console.log("hello")
        if(angular.isArray(myObj)){
          return myObj
        }else{
          return []; 
        }

      }

      

Here is the plunker

0


source







All Articles