app.factory('myService', function ($http) {
var serviceurl = 'http://localhost:12345/Area/Controller/Action/';
var roles = [];
function getRole(id) {
//alert(id);
$http.get(serviceurl + id).success(function (data) {
console.log(data);
roles = data;
})
.error(function (x, y) {
alert('error occurred');
});
}
return {
roles: roles
}
});
我在控制器中将其称为:
app.controller("myController", function ($scope, $http, myService) {
$scope.roles = myService.roles;
});
但$ scope.roles未定义且myService.roles没有值:roles []当我试图在$ scope.roles = myService.roles中放置一个断点时;
我的代码出了什么问题?如何在控制器中调用角色?
答案 0 :(得分:0)
app.factory('myService', function ($http, $q) {
return {
getRole:function(id){
var serviceurl = 'http://localhost:12345/Area/Controller/Action/';
var roles = [];
var p = $q.defer();
$http.get(serviceurl + id).success(function(data) {
console.log(data);
p.resolve(data);
})
.error(function (x, y) {
alert('error occurred');
});
return p.promise;
}
}
});
在您的控制器中:
$scope.roles = myService.getRole(id);