David
David

Reputation: 3614

Controller As inheritance with $controller

I have a pretty big question about this issue but I thought it might be easy to split it in smaller ones.

So, I'm trying to use $controller to inherit from a ParentController, but things are not working as expected.

I have a jsfiddle here. And this is the code.

angular
    .module("app",[])
    .controller('ParentController', ParentController)
    .controller('ChildController', ChildController)

    ParentController.$inject = ['$scope']
    ChildController.$inject = ['$controller', '$scope'];

function ParentController($scope) {
    var vm = this;    

    vm.foo = 'parent foo';
}

function ChildController($controller, $scope) {

    $controller('ParentController as vm', {$scope: $scope});

        var vm = $scope.vm; // view model       
}

And a simple html

<div>
  {{vm.foo}}
</div>

When I configure the app to use the ParentController, with this

<body ng-app="app" ng-controller="ParentController as vm">

it works fine.

But as it is now, with the ChildController, is not working, it's like vm does not include the property foo created in ParentController.

What am I doing wrong?

Many thanks.

Upvotes: 1

Views: 965

Answers (2)

Shrikant
Shrikant

Reputation: 538

enter image description here

HTML

<div>
  {{vm.foo}}
</div>

Controller

  angular
    .module("app",[])
    .controller('ParentController', ParentController)
    .controller('ChildController', ChildController)

    ParentController.$inject = ['$scope']
    ChildController.$inject = ['$controller', '$scope'];

function ParentController($scope) {
    var vm = this;
    vm.obj={};
    vm.obj.foo = 'parent foo';
    console.log('parent',vm.obj);
}

function ChildController($controller, $scope) {

  $controller('ParentController as vm', {$scope: $scope});

    var vm = vm; // view model      
    console.log("child",$scope.vm.obj);
}

Upvotes: 0

dfsq
dfsq

Reputation: 193261

If you really want to go with this approach then you need to extend child controller with base parent controller. You can use angular.extend for this:

function ChildController($controller, $scope) {
    angular.extend(this, $controller('ParentController', {$scope: $scope}));
    this.bar = 'child bar';
}

Just make sure you first extend child controller instance object (this) with parent controller instance, and only after that you define new child properties.

Demo: http://plnkr.co/edit/mdyCOUdZSLUV06AMnoZG?p=preview

Upvotes: 1

Related Questions