如何访问控制器中工厂角色返回的数据?

时间:2013-09-09 11:17:27

标签: angularjs angularjs-controller angularjs-factory

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中放置一个断点时;

我的代码出了什么问题?如何在控制器中调用角色?

1 个答案:

答案 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);