You need to defer, resolve and return your promises in a 'Factory' or 'Services' file.
Then make a call to the respective method in the Factory file in your 'Controller' file.
Factories and Controllers perform totally different functions. All your API calls will
have to be your 'Factory' file and then you can manipulate your data in your
'Controller'
Refer to example below :
//------------------------------------------------------------------------------------
# user.factory.js
# 'app.foo.user' refers to your directory structure i.e. app/foo/user/user.factory.js
(function() {
'use strict';
angular
.module('app.foo.user', [])
.factory('userSvc', UserService);
/* @ngInject */
function UserService(
$log,
$q,
$http,
$window,
$state,
logger,
session,
utils,
API_CONFIG) {
var ENDPOINTS = {
USERS: '/v1/users'
};
/**
* @ngdoc service
* @name app.foo.user
* @description User management
*/
var service = {
get: get
};
/**
* @ngdoc method
* @name get
* @description Returns all users
* @methodOf app.foo.user
* @returms {promise} user or null if not found
*/
function get() {
var q = $q.defer();
var request = utils.buildAuthRequest(session, 'GET', ENDPOINTS.USERS);
$http(request)
.success(function (users) {
q.resolve(users.result);
})
.error(function (error) {
logger.error('UserService.get > Error ', error);
return q.promise;
}
}
})();
//------------------------------------------------------------------------------------
# user.module.js
# 'app.foo.user' refers to your directory structure i.e. app/foo/user/user.module.js
(function() {
'use strict';
angular
.module('app.foo.user', [
]);
})();
//------------------------------------------------------------------------------------
# user-list.controller.js
# This is where you make a call to the 'get' method in the 'user.factory.js' where the promises
# were defered, resolved and returned.
# And you gave to inject 'userSvc' in this file so as to connect to the 'user.factory.js' file.
# 'app.foo.admin' refers to your directory structure i.e. app/foo/admin/user-list.controller.js
(function() {
'use strict';
angular
.module('app.foo.admin')
.controller('UsersListController', UsersListController);
/* @ngInject */
function UsersListController(
$scope,
$state,
$timeout,
$log,
userSvc) {
var vm = this;
vm.loading = false;
vm.userSvc = userSvc;
activate();
function activate() {
// init users
vm.userSvc.get().then(
function(users) {
vm.users = users;
},
function(error) {
$log.error(error);
}
);
}
}
})();
它是路由控制器嗎?如果是這樣,你使用什麼路由器? –