Jimbrooism Jimbrooism - 1 year ago 45
Javascript Question

Order of object is changed

I want to bind dynamic data , after I bind the data the order of data is getting changed

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

app.controller('mainCtrl', function($scope){
$scope.fieldNames = { author_name: "Author Name", about_author: "About author", author_image : "Author Image" };
$scope.authors = [{author_name: 'akshay', about_author:'this is about author', author_image:'image url here'}];


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">

<div ng-repeat="author in authors" class="authorAndTagGroup">
<div ng-repeat="(key, value) in author">
<label class="col-sm-3 control-label">{{fieldNames[key]}}</label>
<input type="text" ng-model="author[key]">


I want to display like

Author Name : akshay

About author : this is about author

author_image : image url here

Answer Source

Yes, the problem will be solved if you use higher version where this issue been resolved(e.g-> 1.5.3).

Working Demo

I suggest you to have a look at the migration doc. It will help you to avoid future problems.

From migration doc:

Due to c260e738, previously, the order of items when using ngRepeat to iterate over object properties was guaranteed to be consistent by sorting the keys into alphabetic order.

Now, the order of the items is browser dependent based on the order returned from iterating over the object using the for key in obj syntax.

It seems that 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues

The best approach is to convert Objects into Arrays by a filter such as https://github.com/petebacondarwin/angular-toArrayFilter or some other mechanism, and then sort them manually in the order you need.