角度范围上的角度环

时间:2014-07-22 08:56:47

标签: javascript angularjs loops

如何循环$scope.properties个对象值并将其放入$scope.coords的单独Angular列表中?

<script type="text/javascript">
    var propertyModule = angular.module(
        'propertyModule', 
        ['ngResource', 'ngMap', 'ngRoute']
    );
    propertyModule.controller(
        'propertyController', 
        [
            '$scope', 
            'Property', 
            function ($scope, Property) {
                // Query returns an array of objects, MyModel.objects.all() by default
                $scope.properties = Property.query();
                // Getting a single object
                $scope.property = Property.get({pk: 1});
                $scope.coords = [];
            }
        ]
    );
</script>

$scope.properties返回一个json:

[
    {
        "city":1,
        "name":"Pastatas A",
        "coordinates":[24.43359375,54.6611237221],"pk":1
    },
    {
        "city":1,
        "name":"hmgbjmnbm",
        "coordinates":[25.2905273438,54.6738309659],
        "pk":4
    },
    {
        "city":1,
        "name":"gfghfghfg",
        "coordinates":[25.3344726562,54.6102549816],
        "pk":3
    },
    {
        "city":1,
        "name":"sdfsdgsdgsdgasssss",
        "coordinates":[25.2685546875,54.6801830971],
        "pk":5
    },
    {
        "city":2,
        "name":"Test flat",
        "coordinates":[25.2960205078,54.6611237221],
        "pk":6
    }
]

我希望$scope.coords仅包含坐标值。 $scope.coords必须在控制器中。

2 个答案:

答案 0 :(得分:0)

您可以这样做:

$scope.coords = [];
for(var i=0;i<$scope.properties.length;i++){
    $scope.coords.push($scope.properties[i].coordinates);
}

Working Fiddle检查控制台

答案 1 :(得分:0)

http://jsbin.com/xudan/1/edit

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

    app.controller('firstCtrl', function($scope){

      $scope.properties  = [
        {
            "city":1,
            "name":"Pastatas A",
            "coordinates":[24.43359375,54.6611237221],"pk":1
        },{
            "city":1,
            "name":"hmgbjmnbm",
            "coordinates":[25.2905273438,54.6738309659],
            "pk":4
        },{
            "city":1,
            "name":"gfghfghfg",
            "coordinates":[25.3344726562,54.6102549816],
            "pk":3
        },{
            "city":1,
            "name":"sdfsdgsdgsdgasssss",
            "coordinates":[25.2685546875,54.6801830971],
            "pk":5
        },{
            "city":2,
            "name":"Test flat",
            "coordinates":[25.2960205078,54.6611237221],
            "pk":6
        }
    ];
      $scope.coords  = [];
      angular.forEach($scope.properties , function(value){

        $scope.coords.push(value.coordinates);

      });
    });