Iterate javascript object keys using angularjs ngRepeat

This tutorial will explain how to get or iterate the JavaScript Object keys / Properties using AngularJs ngRepeat.

It is viable to get ngRepeat to iterate over the houses of an object using the subsequent syntax:

<div ng-repeat="(key, value) in myObj"> ... </div>

ng-repeat for iterate the javascript object properties

Below code will iterate the object keys using ng-repeat

<html ng-app="objectKeyIteration" ng-controller="mainController">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script>
            var app = angular.module('objectKeyIteration',[]);

            app.controller('mainController',['$scope',function($scope){
                $scope.title = "Iterate javascript object key using angularjs ngRepeat";
                $scope.data = {
                    "id":1,
                    "name":"Object Key Iteration",
                    "framework": "angularJS 1.5"
                };
            }]);
        </script>
        <title>{{title}}</title>
    </head>
    <body>
        <div ng-repeat="(key, value) in data">
            <div><strong>{{key}}</strong> : {{value}}</div>
        </div>
    </body>
</html>

However, there are a few limitations compared to array iteration:

  • The JavaScript specification does not define the order of keys returned for an object, so AngularJS relies on the order returned by the browser when running for key in myObj. Browsers generally follow the strategy of providing keys in the order in which they were defined, although there are exceptions when keys are deleted and reinstated. See the MDN page on delete for more info.
  • ngRepeat will silently ignore object keys starting with $, because it’s a prefix used by AngularJS for the public ($) and private ($$) properties.
  • The built-in filters orderBy and filter do not work with objects and will throw an error if used with one.

If you are hitting any of these limitations, the recommended workaround is to convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter or implement a $watch on the object yourself.

W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

Leave a Reply

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