AngularJS $scope inheritance service

时间:2016-02-12 19:46:49

标签: javascript angularjs inheritance angularjs-service

I'm having some trouble with my code. I can't pass nor console.log the inherited $scope.user in my data service. As I'm having this problem also in another situation which looks the same I guess it's because of the callback.

The main Controller creates the user

 .controller('mainCtrl', function ($scope, dataService) {
    dataService.getUser(function (response) {
        $scope.user = response.data[0];
    })

The dataservice

    .service('dataService', function ($http) {
    this.getUser = function (callback) {
        $http.get('mock/user.json')
            .then(callback)
    };

The navigation controller (child of mainCtrl):

    .controller('navCtrl', function ($scope, dataService) {
    //$scope.user = "test";
    console.log ($scope.user);
    dataService.getNavItems($scope.user,function (response) {
        $scope.navItems = response.data;
    });

As you can guess if I set $scope.user manually it works just fine.

3 个答案:

答案 0 :(得分:1)

The promise hasn't resolved yet when navCtrl is instantiated. What you can do is return the promise from $http.get instead of setting scope.user directly in the callback. And then just wrap the call to getNavItems in the promise.

This is assuming, navCtrl is a child of MainCtrl

.service('dataService', function ($http) {
  this.getUser = function () {
    return $http.get('mock/user.json');
  }};

.controller('mainCtrl', function ($scope, dataService) {
    $scope.userPromise = dataService.getUser();
 })

.controller('navCtrl', function ($scope, dataService) {
  $scope.userPromise.then(function(response) {
   var user = response.data[0];
   dataService.getNavItems(user, function (response) {
       $scope.navItems = response.data;
   });
});

})

答案 1 :(得分:1)

The Scope will be different for the two Controllers, therefore it won't be defined in one if you defined it in the other. If you want it to work in both, just use the dataService.

 .service('dataService', function ($http) {
    this.getUser = function () {
       $http.get('mock/user.json').then(function(data) {
          this.user = data;
       )}
};

Then access it in each controller separately, it will be available to both.

答案 2 :(得分:0)

Seems like controllers 'mainCtrl' and 'navCtrl' have different scopes. If the scope of 'navCtrl' is a child of the scope of 'mainCtrl', you can access it with $scope.$parent.user

To trigger logging when the promise is resolved $scope.$parent.$watch('user', fucntion(newVal){console.log(newVal)})

If not, I would suggest to have some kind of context, where you would store the data used by different controllers.

To find a scope you can use angular.element('[ng-controller="mainCtrl"]').scope() even in browser console