Angular.js在控制器中渲染数据

Angular.js render data in controller

本文关键字:数据 控制器 js Angular      更新时间:2023-09-26

我有一个相当简单的问题。我有一个简单的控制器和它的$scope。坐标= [];在HTML中呈现JSON:

[24.43359375, 54.6611237221]
[25.2905273438, 54.6738309659]
[25.3344726562, 54.6102549816]
[25.2685546875, 54.6801830971]
[25.2960205078, 54.6611237221] 

我如何渲染JSON不是在html,但在我的控制器本身?代码是这样的。请参阅代码中的注释:

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  = [];
        $scope.properties = Property.query({}, function(data){
        console.log(data);
        angular.forEach(data , function(value){
            $scope.coords.push(value.coordinates);
        });
        });
        $scope.positions =  //$Resource('realestate.property').items();
        [
        [54.6833, 25.2833], [54.67833, 25.3033] // those coordinates are hardcoded now, I want them to be rendered here by $scope.coords

        ];

    }]);

首先,您向我们展示了一堆数组,而不是JSON文档。但是,由于您的代码似乎正在工作,我将假设您确实有一个有效的JSON来工作。

您需要考虑您在这里发出异步请求的事实:

$scope.properties = Property.query({}, function(data) {
    console.log(data);
    angular.forEach(data , function(value){
        $scope.coords.push(value.coordinates);
    });
});

这意味着您将无法从$scope中获取数据。

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

  • 你可以简单地在你还在循环中获取数据:

    angular.forEach(data , function(value) {
        $scope.coords.push(value.coordinates);
        if('your condition') {
            $scope.positions.push(value.coordinates);
        }    
    });
    
  • 你可以使用promise,参见angular文档。

  • 或者您可以监视$scope。$scope.$watch.