错误加载动态数据ng-repeat

时间:2014-08-27 04:12:18

标签: javascript angularjs angularjs-directive angularjs-ng-repeat

伙计我有一个问题我必须做错事最不知道,似乎google chrome在渲染时或角度组织json使'ng-repeat'。当我在网格中加载数据时,它会反转列反转

    'use strict';

     angular.module('grid', [])
      .run(templateRun)
      .directive('grid', Grid);

    function templateRun ($templateCache) {
        $templateCache.put('grid2.html', '<table><thead><tr><th ng-repeat="(key,value) in option.columns" ng-click="sort(value.predicate)"><strong>{{value.text}}</strong><th><tr></thead><tbody><tr ng-repeat="data in option.data"><td ng-repeat="field in data">{{field}}</td></tr></tbody></table>');
    }

    function Grid ($templateCache, $rootScope, $compile, $rootElement) {

        return{
            restrict: 'E',
            $scope: {
                option: "=data"
            },
            template: $templateCache.get('grid2.html'),
            link: function ($scope, $element, $attr) {

            }

        }

    }


    angular.module("app", ["grid"])
        .controller("HomeCtrl", HomeCtrl);

    function HomeCtrl ($scope) {

        $scope.people = [
            {
                name: "John",
                occupation: "Programmer",
                age: 5
            }, 
            {
                name: "Jill",
                occupation: "Analyst",
                age: 10
            }, 
            {
                name: "Jeff",
                occupation: "Sales",
                age: 2
            }, 
            {
                name: "Joan",
                occupation: "Designer",
                age: 50
            }
        ];

        $scope.option = {
            data: $scope.people,
            columns: [
                {
                    text: "Nome"
                },
                {
                    text: "Ocupação"
                },
                {
                    text: "Idade"
                }
            ]
        }

    }


<!doctype html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>Grid</title>
</head>
<body ng-controller="HomeCtrl">

    <grid data="option"></grid>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript" src="grid.js"></script>
</body>
</html>

错误img:http://i.stack.imgur.com/RpVNe.png

1 个答案:

答案 0 :(得分:1)

可能有几种方法可以解决这个问题。

一种方法是将列名映射到相应的json字段名称,并使用此映射来确定在表的每个单元格中放置哪个字段。

    $scope.option = {
        data: $scope.people,
        columns: [
            {
                text: "Nome",
                dataProp: "name"
            },
            {
                text: "Ocupação",
                dataProp: "occupation"
            },
            {
                text: "Idade",
                dataProp: "age"
            }
        ]
    }

tbody部分html模板

<tbody>
  <tr ng-repeat="data in option.data">
    <td ng-repeat="col in option.columns"> {{data[col.dataProp]}}</td>
  </tr>
</tbody>

工作example