我正在尝试从我们的数据库中检索选项列表,我正在尝试使用angular来执行此操作。我之前从未使用过服务,但我知道如果我要在页面上的其他控制器中使用我的对象中的数据,这将是实现我想要的最佳方式。
我遵循了几个教程并组建了一个生成http请求并返回数据的工厂。我尝试了几种方法,但由于某种原因没有发生任何事情。它就像它从未运行工厂功能,我无法弄清楚为什么。
工厂:
resortModule= angular.module('resortApp',[]);
resortModule.factory('locaService',['$http', function ($http){
var locaService= {};
locaService.locations = {};
var resorts = {};
locaService.getLocations=
function() {
$http.get('/url/url/dest/').success(function (data) {
locaService.locations = data;
});
return locaService.locations;
};
return locaService;
//This is a function I would like to run in addition to the first one so multiple variables would be stored and accessible
/*getResorts:
function(destination) {
$http.get('/url/url/dest/' + destination.id).success(function (data) {
resorts = data;
});
return resorts;
}*/
}]);
resortModule.controller('queryController',['$scope', 'locaService', function($scope, locaService) {
$scope.checkConditional= function (){
if($("#location").val() == ""){
$("#location").css('border','2px solid #EC7C22');
}
};
$scope.selectCheck= function (){
$("#location").css('border','2px solid #ffffff');
$(".conditional-check").hide();
};
$scope.resort;
$scope.locations= locaService.getLocations();
}]);
我只想要返回数据,然后将其分配给$ scope.locations以用于视图中的ng-options。然后我希望我的其他函数在单击时运行,以便由变量求助程序填充下一个字段。我该怎么做?任何帮助都会很棒!谢谢!
答案 0 :(得分:1)
$ http服务返回一个promise,你的函数应该返回该promise。基本上你的getLocations函数应该类似于以下
locaService.getLocations=
function() {
return $http.get('/url/url/dest/');
};
然后在您的控制器中,您应该使用此承诺检索选项:
locaService.getLocations()
.then(
function(locations) // $http returned a successful result
{$scope.locations = locations;}
,function(err){console.log(err)} // incase $http created an error, log the returned error);
在控制器中使用jquery或在控制器中操作dom元素不是一个好习惯,您可以使用ng-style或ng-class直接在视图中应用样式和css类。 以下是一个如何连线的示例:
resortModule= angular.module('resortApp',[]);
resortModule.factory('locaService',['$http', function ($http){
var locaService= {
locations: {}
};
var resorts = {};
locaService.getLocations= function() {
return $http.get('/url/url/dest/');
};
return locaService;
//This is a function I would like to run in addition to the first one so multiple variables would be stored and accessible
/*getResorts:
function(destination) {
$http.get('/url/url/dest/' + destination.id).success(function (data) {
resorts = data;
});
return resorts;
}*/
}]);
resortModule.controller('queryController',['$scope', 'locaService', function($scope, locaService) {
/* Apply these styles in html using ng-style
$scope.checkConditional= function (){
if($("#location").val() == ""){
$("#location").css('border','2px solid #EC7C22');
}
};
$scope.selectCheck= function (){
$("#location").css('border','2px solid #ffffff');
$(".conditional-check").hide();
};
*/
$scope.resort;
locaService.getLocations()
.then(
function(locations) // $http returned a successful result
{$scope.locations = locations;}
,function(err){console.log(err)} // incase $http created an error, log the returned error);
}]);