2

Often times I want to deal with both arrays and single objects in the same fashion. For example I have the property of an object that can either be an array or just a string (look at the scale property):

[
 {
    "name": "Experiment type14",
    "id": "00000000014",
    "scale": ["Whole Brain", "Cell"],

 },
 {
    "name": "Experiment type15",
    "id": "00000000015",
    "scale": "Cell",
 }
]

What I want is to show my scale like here:

<span ng-repeat="scale in experimentType.scale">
 <!--some decoration here--> {{scale}}
</span>

Of course this won't work for a single string values. Is there any elegant way not to worry whether I'm dealing with a string or with an array?

2
  • Personally I think a filter is the best way to handle this. One that unifys the data, so that your view has to only worry about one kind of format. Commented Sep 23, 2014 at 8:06
  • I'm thinking about smth like that too. I love how it's done in jquery: you just wrap stuff in $() and forget about the object/array worries. Commented Sep 23, 2014 at 8:08

2 Answers 2

3

You can create your custom filter, please see below

var app = angular.module("app", []);

function MainCtrl() {
  this.message = "Welcome";
  this.data = [{
    "id": "00000000014",
    "name": "Experiment type14",        
    "scale": ["Whole Brain", "Cell"],
   },{
    "id": "00000000015",
    "name": "Experiment type15",
    "scale": "Cell",
   }];  
}

function toArray() {
  return  function(input) {
    console.log(input);
    if (angular.isArray(input)) {
      return input;
    } else {
      return [input];
    }
  };
}

angular.module("app").controller("MainCtrl", MainCtrl);
angular.module("app").filter('toArray', toArray);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="MainCtrl as vm">
    <div class="container">
       <h3>{{ vm.message }}</h3>
      <div ng-repeat="item in vm.data">
        <p>{{ item.name }}</p>
        <ul>
          <li ng-repeat="scale in item.scale | toArray">{{ scale }}</li>
        </ul>
      </div>
    </div>
  </div>
</body>

Sign up to request clarification or add additional context in comments.

Comments

0

That's my best try. I just implement the following function in the scope:

$scope.toArrayIfNot = function (input) {
        if (Object.prototype.toString.call(input) === '[object Array]') {
            return input;
        }
        return [input];
    };

I then use it like that:

<span ng-repeat="scale in toArrayIfNot(experimentType.scale)">
 <!--some decoration here--> {{scale}}
</span>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.