I was about to covert my code to use controller as
syntax after reading a few articles about it. However, I was surprised that using the controller as
syntax one can no longer use parent controller's variable directly, what I mean is, in the old way (with $scope), I can do this:
// <div ng-controller="ParentCtrl">
// <div ng-controller="ChildCtrl"></div>
// </div>
//
app.controller('ParentCtrl', function ($scope) {
$scope.x.title = 'Some title';
});
app.controller('ChildCtrl', function ($scope) {
console.log($scope.x.title);
});
But with controller as
, I have to do this(thanks to this question):
// <div ng-controller="ParentCtrl as pc">
// <div ng-controller="ChildCtrl as cc"></div>
// </div>
//
app.controller('ParentCtrl', function () {
this.x.title = 'Some title';
});
app.controller('ChildCtrl', function ($scope) {
console.log($scope.pc.x.title);
});
This is quite annoying because 1). I have to know that in the html page my parent controller is named as pc. 2). I can not do a bulk search and replace of $scope => vm (or this)
because it won't work if the property is inherited.
Can anyone please tell me what's the rationale behind this when controller as
is introduced?
Am I right if I use a lot of scope inheritance then I should avoid controller as
? Or is scope inheritance considered harmful in general and should be discouraged?