can i inherit a parent controller's variables?

后端 未结 5 686
北恋
北恋 2021-02-01 15:34

Here is my code:

function ParentCtrl($scope) {
$scope.people = [\"Tom\", \"Dick\", \"Harry\"];
$scope.count = $scope.people.length;
}

function ChildCtrl($scope)         


        
5条回答
  •  温柔的废话
    2021-02-01 15:43

    You're getting things wrong. You are mixing controller inheritance with scope inheritance, and they are different and loosly coupled in AngularJS.

    What you actually want is:

    function ParentCtrl($scope) {
        $scope.people = ["Tom", "Dick", "Harry"];
        $scope.count = $scope.people.length;
    }
    
    function ChildCtrl($scope) {
        $scope.parentpeople = $scope.$parent.people;
    }
    

    And it will work for the case:

    But as Mark and ganaraj noticed above, this has no sense, as you can access your property of $scope.people from both ParentCtrl and ChildCtrl.

    If you want to inherit controllers from each other, you need to use prototype inheritance of controller functions themselves.

提交回复
热议问题