如何在AngularJs中将json数组转换为js数组
How do I turn a json array into a js array in AngularJs?
我刚开始从事Angular和前端开发,似乎无法解决以下问题。
我已经将一个变量重新分配给另一个:$scope.testarray=$scope.todos;但是当使用Angular绑定时,将只显示"todos"。
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;
});
CCD_ 1被写入该块之外。$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;
});
});
相关文章:
- 使用JS将数组转换为json对象
- 本地存储中的字符串到字节数组转换
- Javascript函数,用于将数组转换为“;2-元组”;
- php数组转换为javascript
- 在Javascript中将一个值和字符串数组转换为if语句
- 将数组转换为javascript格式的字符串
- 如何将数组转换为有效的json
- JSON数组转换为JS对象数组
- 如何将数组转换为映射
- JavaScript:将字符串数组转换为文本区域
- javascript |数组转换
- 数组转换为多个字符串
- Javascript将数组转换为字符串并使其反向输出
- 将Byte数组转换为Angularjs中的Base64字符串
- 将对象数组转换为与nodejs/pg/unnest兼容的数组
- 将Javascript数组转换为PHP数组
- 将数组转换为键值对
- 使用Ramda将对象数组转换为普通对象
- javascript将对象数组转换为字符串以存储在s3中
- 使用.join方法将数组转换为不带逗号的字符串