Reading Object Elements in Angular

Not sure why you can’t use ng-repeat, but an alternative option would be using Object.keys to get at the first property of your object, here is an example


<div ng-app="app" ng-controller="ctrl">
  <span>{{getFirstPropertyKey(me)}}</span>
  <span>{{getFirstPropertyValue(me)}}</span>
</div>


angular.module("app", [])
  .controller("ctrl", function($scope) {
      $scope.me = {
          "name": "Ealon" //This object only contains one key
      };

      $scope.getFirstPropertyKey = function(obj){
        return Object.keys(obj)[0];
      }

      $scope.getFirstPropertyValue = function(obj){
        return obj[Object.keys(obj)[0]];
      }
  });

Leave a Reply

Your email address will not be published. Required fields are marked *