我有一个相当简单的问题。我有一个简单的 Controller 及其 $scope.coords = [];在 HTML 中呈现 JSON:
[24.43359375, 54.6611237221]
[25.2905273438, 54.6738309659]
[25.3344726562, 54.6102549816]
[25.2685546875, 54.6801830971]
[25.2960205078, 54.6611237221]
如何在 Controller 本身中而不是在 html 中呈现该 JSON?代码看起来像这样。请看代码中的注释:
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.coords 获取数据。
有几种方法可以解决这个问题:
您可以在循环中时简单地获取数据:
angular.forEach(data , function(value) { $scope.coords.push(value.coordinates); if('your condition') { $scope.positions.push(value.coordinates); } });
您可以使用 Promise,请参阅 angular doc .
或者您可以使用 $scope.$watch 监视 $scope.coords。
关于javascript - Angular.js 在 Controller 中渲染数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24910883/