angularjs:如何使用controllerAs访问模板中隔离作用域指令的属性

angularjs: how to use controllerAs to access the property of the isolated scope directive in template

我在我的Angularjs项目中通常使用controllerAs语法,我认为在模板中会更清楚。
但是在当前的网络应用程序中,我遇到了如下问题:

function FirstCtrl() {
    this.name = 'First Controller';
}

function fooDirective() {
    return {
        scope: {
            testData:'='
         },
        name: 'ctrl',
        controller: 'FirstCtrl',
        controllerAs: 'foo',
        template: '<div>{{ foo.name }} {{testData}} {{foo.testData}}</div>',
        link: function ($scope, $element, $attrs, $ctrl) {
             console.log($ctrl.name);
        }
    };
 }

angular
    .module('app', [])
    .directive('fooDirective', fooDirective)
    .controller('FirstCtrl', FirstCtrl);

html部分如下:

<div ng-app="app">
    <foo-directive test-data="'newdata'"></foo-directive>
</div>

现场演示在这里:
https://jsfiddle.net/baoqger/rbp1wyfa/

而我的困惑点在模板部分:

template: '<div>{{ foo.name }} {{testData}} {{foo.testData}}</div>',

{{testData}}可以正常工作。但是 {{foo.testData}} 不能。如何解决此问题,以便我以 controllerAs 方式访问隔离范围对象中的 属性。

您想将 bindToController: true 添加到您的指令定义中:

function fooDirective() {
    return {
        scope: {
            testData:'='
         },
        name: 'ctrl',
        controller: 'FirstCtrl',
        controllerAs: 'foo',
        bindToController: true,
        template: '<div>{{ foo.name }} {{testData}} {{foo.testData}}</div>',
        link: function ($scope, $element, $attrs, $ctrl) {
             console.log($ctrl.name);
        }
    };
}

适用的文档是 here(请注意,您必须向上滚动一点,以了解它们的浮动 menu/header)。