为什么 JavaScript 中的 `controllerAs` 有效,但 HTML 中的 ng-controller=...as... 无效?

Why does `controllerAs` in JavaScript work but not `ng-controller=...as...` in HTML?

这个有效:

Plunker controllerAs in js

输入-form.html

<form name="inputForm" ng-submit="inputForm.$valid && inputCtrl.emitData()" novalidate>
  <textarea name="topic1Data" ng-model="inputCtrl.inputValues.topic1Data" rows="10" cols="30" required></textarea>
  <button type="submit" class="btn btn-info btn-lg" ng-disabled="!inputForm.$valid">Compare</button>
</form>

inputForm.js

"use strict";

(function() {
  var inputForm = angular.module('input-form', []);

  inputForm.directive('inputForm', function() {
    return {
      restrict: 'E',
      templateUrl: 'input-form.html',
      scope: {data: "="},
      controllerAs: 'inputCtrl',
      bindToController: true,
      controller: function() {
        var inputCtrl = this;
        inputCtrl.inputValues = {topic1Data: 123456789};

        inputCtrl.emitData = function() {
          inputCtrl.data =  inputCtrl.inputValues.topic1Data;
        };
      }
    };
  });
})();

来源:

这不起作用:

Plunker controller as in html

输入-form.html

<form name="inputForm" ng-controller="InputController as inputCtrl" ng-submit="inputForm.$valid && inputCtrl.emitData()" novalidate>
  <textarea name="topic1Data" ng-model="inputCtrl.inputValues.topic1Data" rows="10" cols="30" required></textarea>
  <button type="submit" class="btn btn-info btn-lg" ng-disabled="!inputForm.$valid">Compare</button>
</form>

inputForm.js

"use strict";

(function() {
  var inputForm = angular.module('input-form', []);

  inputForm.directive('inputForm', function() {
    return {
      restrict: 'E',
      templateUrl: 'input-form.html',
      scope: {data: "="},
      bindToController: true
    };
  });

  inputForm.controller('InputController', function(){
    var inputCtrl = this;
    inputCtrl.inputValues = {topic1Data: 123456789};

    inputCtrl.emitData = function() {
      inputCtrl.data =  inputCtrl.inputValues.topic1Data;
    };
  });
})();

我发现一个 article by Pascal Precht 似乎说解决方案是 bindToController 但我正在使用 bindToController 但它仍然不起作用。

为什么 JavaScript 中的 controllerAs 有效而 HTML 中的 ng-controller=...as... 无效?

bindToController 使用在指令定义对象上定义的控制器:

.directive("foo", function(){
  return {
    //..
    bindToController: true,
    controller: "FooCtrl",
    controllerAs: "foo"
  };
});

换句话说,当 $compile 服务运行和 compiles/links 指令时,它会收集指令并绑定到 directive.controller 对象。那是 "binds" 隔离作用域属性的控制器。

在您的情况下,您假设(错误地)在模板中使用 ng-controller="FooCtrl as foo" 定义的控制器将以相同的方式工作。该假设没有依据,您链接到的文章从未将其显示为一个选项。

该模板可以实例化多个控制器,更不用说模板可以异步加载(使用 templateUrl),因此 bindToController 从来没有打算以这种方式使用。