Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - ng-repeat looping partially over an object

I am developing a simple program (in concept) but unfortunately. I have com upon the problem and days of googling have not resulted in anything.

I'm trying to loop through an object, and all it's children. I've done this with two ng-repeats which in theory seems pretty sound and fool-proof

Here's my current code:

(function() {

  var CHEAT = angular.module('cheat', []);
  CHEAT.controller('maps', function($scope) {
    $scope.search = "";
    $scope.range = {
      "Globals": {
        "$": "M",
        "M": {
          "z": "q"
        }
      },
      "Other": {
        "S": {
          'c': "cat"
        }
      }
    };
    $scope.type = function(obj) {
      return typeof obj;
    };
  });

}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="info" ng-app="cheat" ng-controller="maps">
  <div ng-repeat="(res, prop) in range">
    {{prop}} =
    <div ng-repeat="(key,test) in prop">
      {{key}}: {{test}}
    </div>
  </div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've stumbled across a gotcha in Angular.

Keys that begin with dollar sign ($) will not be recognized by an ng-repeat ($ is a reserved character in angular and other frontend libraries).

Link to the Github issue (currently seems to be a do-not-fix):

Example fiddle: http://jsfiddle.net/takvg/4/

From the github issue mentioned above, there is a workaround from frfancha:

Workaround is easy: just make your ng-repeat on Object.keys(myObject)

For instance:

$scope.thing = {
    "Globals": {
        "$": "M",
            "M": {
            "z": "q"
        }
    },
        "Other": {
        "S": {
            'c': "cat"
        }
    }
};
$scope.range = Object.keys($scope.thing);

You'll be dealing with an array instead of an object, so your ng-repeat will need to change a little bit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...