3

I'm pretty new to (real) javascript and new to Angular

I'm writing an app for home automation. The app returns a list of devices and then when you click on a device, it returns it's details via JSON (Example below). The problem I have is that different device types return different name value pairs in the object and I won;t know these in advance. (For example a light switch will return a dim level, but a thermostat returns a sensor level.

Obviously, my app can only do stuff with know properties (e.g. set dim level if it's a light), but the user may want to see all the properties. Is their a way to use ng-repeat to list all the name value pairs without knowing the property names?

Example:

 {
    "name": "1-Wire Test1",
    "address": 0,
    "addressStr": "unknown",
    "classID": 3,
    "devProtocol": 999,
    "displayInUI": true,
    "displayLongState": "76.7 °F",
    "displayRawState": "76.700000",
    "folderID": 1418405935,
    "hasStateToDisplay": true,
    "id": 704024169,
    "lastChanged": 456266814,
    "lastChangedDateStr": "2014-06-16",
    "lastChangedRFC3339": "2014-06-17T01:46:54Z",
    "lastChangedRFC822": "Tue, 17 Jun 2014 01:46:54 GMT",
    "lastChangedTimeStr": "08:46:54 PM",
    "sensorValue": "76.7 °F",
    "type": "1-Wire Temperature Sensor",
    "typeFlags": 81,
    "typeSupportsDim": false,
    "typeSupportsEnergyMeter": false,
    "typeSupportsHVAC": false,
    "typeSupportsIO": false,
    "typeSupportsOnOff": false,
    "typeSupportsSensorValue": true,
    "typeSupportsSpeedControl": false,
    "typeSupportsSprinkler": false,
    "versByte": 0,
    "restParent": "devices"
}
Mel
  • 5,837
  • 10
  • 37
  • 42
mark1234
  • 1,110
  • 2
  • 24
  • 41

2 Answers2

13

Of course, use the (k, v) in o repeat syntax:

Eg:

<span ng-repeat="(property, value) in phoneProperties">{{property}} : {{value}}</span>
tymeJV
  • 103,943
  • 14
  • 161
  • 157
2
var anObject = {randomName: "foo",
                randomNameNumber100: "bar"};

In the template

<div ng-repeat="(key, val) in anObject">
  <p>{{ key }}</p>
  <p>{{ val }}</p>
</div>

This will display your object based on the key, in a sorted manner.

Faris Nasution
  • 3,450
  • 5
  • 24
  • 29
  • How does this sorting look like? IMHO the output would be the same as determined in the original array, no?.For sorting stuff, one would need to use something like to use a filter like "OrderBy", see: https://stackoverflow.com/questions/14478106/angularjs-sorting-by-property – Pille Jul 19 '17 at 07:55