更新: 我已经弄明白并解决了这个问题。做我希望在这里完成的事情。执行以下操作:
var app = angular.module('myApp', []);
app.factory('server', ['$http', function($http) {
return {
getResults: function(blah) {
var req = {};
req.blah = blah;
return $http({
method: 'GET',
url: 'blah',
params: req
});
}
}
}]);
app.controller('myCtrl', ['$scope', 'server', function($scope, server) {
$scope.getResults = function() {
server.getResults($scope.blah)
.success(function(data) {
$scope.results = data;
}).error(function(data) {
$scope.results = {
"Blah": "something"
};
});
};
}]);
原帖: 我的目标是让UI对RESTful服务器执行GET请求,并获得JSON作为回报。所以在我的myApp.js中,我有:
var app = angular.module('myApp', []);
app.factory('server', ['$http', function($http){
var server = {};
server.getResults = function(blah) {
return $http({
method: 'JSONP',
url: 'blah'
});
}
return server;
}]);
app.controller('MainCtrl', ['$scope', function($scope, server){
$scope.results = server.results;
}]);
我应该澄清一下,我应该从服务器获得的响应是一个JSON对象,如下所示:
var blah = {"Blah": "something"}
答案 0 :(得分:1)
你的js应该是这样的:
var app = angular.module('myApp', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
})
$urlRouterProvider.otherwise('home');
}]);
app.factory('frontend_server', ['$http', function($http){
return {
getResults = function(colors, stops) {
var results = null;
var req = {
colors:colors,
stops: stops
}
return $http({
method: 'GET',
url: 'blah',
params : req
});
}
}
}]);
app.controller('MainCtrl', ['$scope','frontend_server', function($scope, frontend_server){
$scope.colors = null;
$scope.stops = null;
frontend_server.getResults($scope.colors, $scope.stops).success(function(data){
$scope.results = = data;
}).error(function(data){
$scope.results = = data;
});;
}]);