对象的顺序已更改

Order of object is changed

本文关键字:顺序 对象      更新时间:2023-09-26

我想绑定动态数据,绑定数据后数据的顺序发生了变化

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>

我想显示像

作者姓名 : 阿克谢

关于作者

:这是关于作者的

author_image : 图片网址在这里

是的,如果您使用解决此问题的更高版本(例如-> 1.5.3),问题将得到解决。

工作演示

我建议您查看迁移文档。它将帮助您避免将来出现问题。

从迁移文档:

由于 c260e738,以前,使用 ngRepeat 到 对对象属性的迭代保证是一致的 按字母顺序对键进行排序。

现在,项目的顺序取决于浏览器的顺序 从使用for key in obj循环访问对象返回 语法。

似乎浏览器通常遵循提供密钥的策略 按照它们的定义顺序,尽管有例外 删除并恢复密钥时。看 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues

最好的方法是通过过滤器将对象转换为数组,例如 作为 https://github.com/petebacondarwin/angular-toArrayFilter 或一些 其他机制,然后按所需顺序手动排序。

您应该始终显式定义属性名称,因为永远无法保证每个(如 ng-repeat)循环的排序。

所以我建议使用单个循环(而不是嵌套循环),如下所示:

<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>

当我将角度版本 1.2.23 更改为 1.5.3 时,问题得到了解决