如何使用"controller as"语法继承基本控制器?

bla*_*238 2 javascript angularjs angularjs-scope

这是一个片段,演示如何使用$controller和继承基本控制器$scope:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, $controller) {
  $controller('BaseCtrl', {
    $scope: $scope
  })
});

app.controller('BaseCtrl', function($scope) {
  $scope.name = 'World';
});
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

如何使用"控制器为"语法执行相同操作?这个片段演示了我的目标,但它不起作用:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, $controller) {
  $controller('BaseCtrl', {
    $scope: $scope
  })
});

app.controller('BaseCtrl', function() {
  this.name = 'World';
});
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

PSL*_*PSL 7

您可以使用控制器作为语法(或只使用$controller提供程序返回的ctrl实例)并使用angular.extend.但我不认为有另外一种方式隐式角度可以做到这一点,因为"控制器为"语法最终将控制器实例作为指定为别名的属性名称放在相应的范围上.但这实际上不是继承,而是利用对象扩展.

var ctrl = $controller('BaseCtrl as base', { //You don't really need to use as syntax here though
   $scope: $scope
});

angular.extend(this, ctrl);
Run Code Online (Sandbox Code Playgroud)
//or

$controller('BaseCtrl as base', { //You don't really need to use as syntax here though
   $scope: $scope
});
angular.extend(this, $scope.base); //With as syntax 
Run Code Online (Sandbox Code Playgroud)

或者您可以在控制器构造函数本身的实现级别使用原型继承.有很多可用的语法糖,extends这里还有另一个很好的简单例子.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, $controller) {
 var ctrl = $controller('BaseCtrl as base', {
    $scope: $scope
  });
 
  angular.extend(this, ctrl);
});

app.controller('BaseCtrl', function() {
  this.name = 'World';
});
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)