Daniel Barde
Daniel Barde

Reputation: 2703

Angular Nested Controller Scope Inheritance Problem

I'm having some weird problem here I have already declared a scope data in my main controller and can access it in every other controller except this child controller I just made, when I log/use $scope.user in the child controller the value is undefined

Main Controller

(function(){
    angular.module('app.ctrls', []);
        var app = angular.module('app.ctrls');
        app.controller('mainCtrl', ["$scope", function($scope){
            $scope.user = {
                name:"John Doe",
                id: 4
            };
    }]);
})();

Child Controller

(function(){
    var app = angular.module("app.ctrls");
    app.controller("childCtrl", ["$scope", function($scope){
        console.log($scope.user);
    }]);
})();

Route

var app = angular.modules("app.configs");
    app.config(['$routeProvider', '$locationProvider', function ( 
    $routeProvider, $locationProvider ) {
        $routeProvider
        .when('/settings/basic_info', {
            templateUrl: 'basic_info_settings.html',
            controller: 'childCtrl',
            title: 'Basic Info - Settings | Knoweldge First'
        })
}]);

View

<div ng-controller="mainCtrl" ng-view> 

</div>

Upvotes: 0

Views: 331

Answers (1)

Artyom Pranovich
Artyom Pranovich

Reputation: 6962

1) This issue related with your html structure.

If you want to inherit parent's controller scope, you should create nested structure of your controllers on the view. You can restructure your html smth like this:

<div ng-controller="MainCtrl">
    <div ng-view></div>
</div>

In this case angular will know, that every new controller's scope should be inherited from parent's controller scope.

I've created JSFiddle example for you with the same case.

2) Also you can solve this problem with using of resolve object.

For example:

.when('/settings/basic_info', {
            templateUrl: 'basic_info_settings.html',
            controller: 'childCtrl',
            resolve: {
               user: function(userService){
                  return userService.getUser();
               }
            }
        })

Where userService:

app.factory("messageService", function($http){
    var factory = {
       getUser: function() {
          var promise = $http({ 
              method: 'GET', 
              url: 'api/user'
          })
          .success(function(data) {
              return data;
          });
          return promise;
       }
    };
    return factory;
});

Angular show this route only when all promises will be resolved and you can just use user object, which is injected into the controller.

app.controller("childCtrl", ["$scope", user, function($scope, user){
     $scope.user = user;
}]);

Upvotes: 1

Related Questions