我希望这是一个容易回答的问题...
我试图创建一个加载我的json的表,然后能够单击一行并加载更多与json对象相关的细节。当您单击一行时,它应该在页面顶部加载其他详细信息。行点击部分工作正常。我遇到的问题是默认加载初始对象。
以下是我所指的一个例子:
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
$scope.select = function (item) {
$scope.selected = item;
}
}]);
http://embed.plnkr.co/6LfAsaamCPPbe7JNdww1/
我尝试在$ scope.select之后添加它,但出现了错误:
$scope.selected = item[0];
如何默认加载json中的第一个对象?
提前致谢
答案 0 :(得分:1)
在您的promise内部,resolve函数将数组的第一项指定为选定值:
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log(data);
});
答案 1 :(得分:0)
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log($scope.itemDetails);
console.log($scope.selected);
});
}]);