Here is a snippet demonstrating how to inherit from a base controller using $controller
and $scope
:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $controller) {
$controller('BaseCtrl', {
$scope: $scope
})
});
app.controller('BaseCtrl', function($scope) {
$scope.name = 'World';
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>
How can I do the same using "controller as" syntax? This snippet demonstrates what I am after, but it doesn't work:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $controller) {
$controller('BaseCtrl', {
$scope: $scope
})
});
app.controller('BaseCtrl', function() {
this.name = 'World';
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as main">
<p>Hello {{main.name}}!</p>
</body>
</html>