0

Is there a convenient way to read key/value from an object with only one key in AngularJS expression? Below is an example.

<div ng-app="app" ng-controller="ctrl">
    <span>{{me.key}}</span> //I want: <span>name</span>
    <span>{{me.value}}</span> //I want: <span>Ealon</span>
</div>

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

Using ng-repeat to display the key/value pair is a solution. But unfortunately, I cannot use ng-repeat here for some reason.

Another solution, which I think is not convenient, is:

<div ng-app="app" ng-controller="ctrl">
    <span>{{meCopy.key}}</span>
    <span>{{meCopy.value}}</span>
</div>

angular.module("app", [])
    .controller("ctrl", function($scope) {
        $scope.me = {
            "name": "Ealon"
        };

        var meKey = Object.getOwnPropertyNames($scope.me)[0];
        var meValue = $scope.me[meKey];

        $scope.meCopy = {
            "key": meKey,
            "value": meValue
        };
    })

Is there any simpler way to do this? Thanks for your help!

2 Answers 2

1

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, e.g.:

<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]];
      }
  });
Sign up to request clarification or add additional context in comments.

Comments

1

But unfortunately, I cannot use ng-repeat here for some reason.

Probably you tried to put the ng-repeat directive on the same element as the ng-controller directive. Both those directives create scopes and will fight each other.

The ng-repeat directive needs to be on a different element than the ng-controller directive.

<div ng-app="app" ng-controller="ctrl">
     <div ng-repeat="(key, value) in me">
        <span>{{key}}</span>
        <span>{{value}}</span>
     </div>
</div>

By placing the two directives on different elements, scopes created by the ng-repeat will properly inherit from the scope created by the ng-controller directive.

The DEMO on JSFiddle

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.