byteC0de
byteC0de

Reputation: 5273

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'}];
  console.log($scope.authors);
  
});
<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]">
      </div>
    </div>

</div>

I want to display like

Author Name : akshay

About author : this is about author

author_image : image url here

Upvotes: 2

Views: 65

Answers (3)

Khalid Hussain
Khalid Hussain

Reputation: 1694

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.

Upvotes: 3

byteC0de
byteC0de

Reputation: 5273

The problem got solved when i am changed my angular version 1.2.23 to 1.5.3

Upvotes: 0

NightCabbage
NightCabbage

Reputation: 489

You should always explicitly define your property names, as ordering in for each (like ng-repeat) loops is never guaranteed.

So i would recommend a single loop (instead of a nested loop), as follows:

<div ng-repeat="author in authors" class="authorAndTagGroup">
    <label class="col-sm-3 control-label">Author Name</label> 
    <input type="text" ng-model="author_name">
    <label class="col-sm-3 control-label">About Author</label> 
    <input type="text" ng-model="about_author">
    <label class="col-sm-3 control-label">Author Image</label> 
    <input type="text" ng-model="author_image">
</div>

Upvotes: 0

Related Questions