2

How can I achieve the following using Controller-As approach:

app.controller("parentCtrl", function($scope){
   $scope.parentObj = {prop1: "not set", prop2: "something"};
   $scope.doSomething = function(){...}
})
.controller("childCtrl", function($scope){
   $scope.parentObj.prop1 = "changed";
});

<div ng-controller="parentCtrl">
  {{prop1}}
  <div ng-controller="childCtrl">
    {{prop2}}
    <button ng-click="doSomething()">Do</button>
  </div>
</div>

without making assumptions about how the parent controller is aliased in the view, i.e. no {{pc.prop2}}.

In other words, I would like to benefit from scope inheritance while using Controller-As approach. The question is How?

app.controller("parentCtrl", function(){
   this.parentObj = {prop1: "not set", prop2: "something"};
   this.doSomething = function(){...}
})
.controller("childCtrl", function($scope){

   // $scope.parentObj is undefined!
});
New Dev
  • 48,427
  • 12
  • 87
  • 129
  • 1
    It's not. I specifically asked "without making assumptions about how the parent controller is aliased". The answer you linked to doesn't provide this solution – New Dev Oct 30 '14 at 23:44
  • $scope.$parent is not the alias of the parent for me – yunandtidus Oct 30 '14 at 23:47
  • 1
    No, it's not - although that doesn't use the inherited scope (what if it's `$parent.$parent`?) But in any case, with Controller-As, one defines the ViewModel with `this.vmProperty`, rather than `$scope.vmProperty`. With this, `$scope.$parent.vmProperty` is undefined. – New Dev Oct 30 '14 at 23:53
  • Well... you can't the whole idea of controller as is to be explicitly used on the view. So you could use Controller As, you could use $parent and you could also use the dot notation like you did. I really can't see where you're trying to get in this question – Linial Oct 31 '14 at 00:41
  • Amended the question to clarify – New Dev Oct 31 '14 at 01:35
  • @NewDev did you found the answer? I'm stuck with the same questions – Pedro Justo Dec 03 '14 at 15:18
  • @PedroJusto, I've [answered my own question](http://stackoverflow.com/questions/26647460/accessing-inherited-scope-with-controller-as-approach) that is related to this one. – New Dev Dec 04 '14 at 03:36

1 Answers1

3

When you are using as syntax to define a controller then to access parent scope variable in child controller use following :

var userData = $scope.parentCtrl.user;

Where parentCtrl is name of parent controller using as syntax and user is a variable defined in same controller.

Rubi saini
  • 2,515
  • 23
  • 21
  • I specified in the question (in bolded text): "without making assumptions about how the parent controller is aliased in the view" – New Dev Jul 19 '15 at 13:39