我想在$http.get()
中传递Array对象。以前所有信息都存储在data.json
文件中,但我不想使用文件。想要在控制器中将对象数组定义为$scope.data
。
请找 DEMO
http://plnkr.co/edit/X5ZC3UGey4Zjos7W01U1?p=preview
工作演示http://plnkr.co/edit/o6EeKnC8oFEq3GCRsQgp?p=preview 这里我们使用的是data.json。我想在Controller中定义data.json里面的数据,Plz告诉我如何dd
.controller('QuestionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.questions = [];
$scope.data = {
"questions": [
{
"question": "Qw1",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
},
{
"question": "Qw2",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
}
]
}
$http
.get(JSON.stringify($scope.data))
.then(function(response){
$scope.questions = response.data.questions;
});
}])
答案 0 :(得分:1)
我正在使用它,它对我很有用
$http.get('url', {params: yourArray}).then(function (result) {
//do sth with data
});
答案 1 :(得分:0)
HTTP GET请求不能包含要发送到服务器的数据。您可以向请求添加查询字符串。 $http
选项为params
。
$http({
url: 'example.com',
method: "GET",
params: {...}
});
答案 2 :(得分:0)
如果数据直接在控制器中可用,则不需要使用$ http.get()。
You can use $scope.data instead of $scope.questions. ie in your html file use
{{data.questions[0].question}}
<h2>answer 1</h2>
<p>{{data.questions[0].answers[0].value}}</p>
<p>{{data.questions[0].answers[0].answers}}</p>
答案 3 :(得分:0)
我试过这种方式并且工作正常: 例如,在您的控制器中,您有任何数组,如arr变量
var data = Array;
data['Id'] = "1";
data['Name'] ="Test User";
data['UserName'] = "test_user";
data['Email'] = "test@gmail.com";
data['Address'] = "Test Address";
data['Action'] = 'Create';
要传递此数组,您可以像这样使用
$scope.users = data;
控制器在视图页面中发送一个数组作为变量users
你可以使用这样的东西
ng-repeat="user in users"
注意:这适用于二维数组和一维数组。
答案 4 :(得分:0)
AngularJS具有$http
服务,以异步方式获取数据。所以它可以返回任何类型的数据(变量,数组,字符串)。
最好将数据存储在一些常见的地方。让我展示 factory 模式,用于在控制器之间共享数据。
首先,您应该创建yourFactory.js
文件并编写以下代码:
(function () {
var yourFactory = function () {
var persons = [
{
id: 1,
name: 'Jon',
},
{
id: 2,
name: 'Ben',
},
{
id: 3,
name: 'Joseph',
},
{
id: 4,
name: 'Adam',
}
];
var factory = {};
factory.getPersons = function () {
return persons;
};
return factory;
};
angular.module('personsApp').factory('personsFactory', yourFactory);
}());
有些控制器可以使用数据(只需为以下控制器创建新的.js
文件):
(function()
{
debugger;
var yourController=function($scope, yourFactory) {
/*alert('a1');*/
debugger;
function init() {
debugger;
$scope.yourData=yourFactory.getPersons();
}
init();
};
yourController.$inject=['$scope', 'yourFactory'];
angular.module('yourAppl').controller('yourController', yourController);
}());