cheziHoyzer
cheziHoyzer

Reputation: 5021

ng-repeat on non array object

I know that ng-repeat works only on array.

My problem is when I don't know if the object that I get from the server, is array, or only object.
I need to determine dynamically if it's array or object, and only if it's array use ng-repeat.

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

I tried to solve the problem this way:

 <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's not working.

Upvotes: 4

Views: 3207

Answers (3)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

This can be achieved in another way also.

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 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

Upvotes: 0

David Votrubec
David Votrubec

Reputation: 4156

Priority of directives might be issue but I would argue that in the cause the real cause is elsewhere.

Angular tries to search for definion of Array.isArray() on the current $scope. And can not find it.

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

something like this

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>

Upvotes: 0

Mukund Kumar
Mukund Kumar

Reputation: 23191

ng-repeat priority is 1000 and ng-if priority is 600. so ng-repeat execute first and then ng-if.that's why your code not working .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>

Upvotes: 7

Related Questions