[英]How do I turn a json array into a js array in AngularJs?
我開始進行Angular和前端開發,似乎無法解決以下問題。
我已經將一個變量重新分配給另一個變量:$ scope.testarray = $ scope.todos; 但是使用Angular綁定時,只會顯示“待辦事項”。
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
$scope.testarray = $scope.todos;
});
和html:
<!doctype html>
<html ng-app="App" >
<head>
<meta charset="utf-8">
<title>Todos $http</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />"); </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="TodoCtrl">
<ul>
<li ng-repeat="todo in todos">
{{todo.text}} - <em>{{todo.done}}</em>
</li>
</ul>
this doesn't display: {{testarray}}
</br></br>
but this does dislay: {{todos}}
</body>
</html>
在你的代碼中
App.controller('TodoCtrl', function($scope, $http) { $http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
}); //.then block ends here
$scope.testarray = $scope.todos;
});
$scope.testarray = $scope.todos;
寫在then塊之外。 $http.get
是一個異步調用,因此,即使在定義$scope.todos
之前,也將執行此行。
將其移入.then
塊將解決您的問題。 假設在這里聲明了$scope.testarray
。
App.controller('TodoCtrl', function($scope, $http) { $http.get('todos.json').then(function(res){ $scope.todos = res.data; $scope.testarray = $scope.todos; //Moved inside }); });
如果您需要更多幫助,請發表評論。
我只會使用$scope.$watch
,
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
$scope.testarray = $scope.todos;
$scope.$watch('todos', function(newValue, oldValue) {
$scope.testarray = newValue;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.