angularjs - 无法在指令模板中使用指令 Controller 值

标签 angularjs angularjs-directive scope attributes

我很难访问从该指令模板传递到我的指令的属性。我希望能够从 album.tmpl.html 访问“companyId”,但无论我如何尝试,我都无法获取它。最奇怪的部分是我可以看到它已经进入 Controller ,但不知何故它没有从 Controller 进入模板。我知道模板正确地调用了 Controller ,因为它可以成功打印出在 Controller 内部初始化的“testVar”的值。任何建议将不胜感激。

指令+指令 Controller

(function () {
'use strict';
angular.module('erCommon')
    .directive('erAlbum', albumDirective)
    .controller('AlbumController', AlbumController);

function AlbumController() {
    var vm = this;
    vm.testVar = "test var initiated";
}

function albumDirective($log) {
    function albumLink(scope, element, attrs, AlbumController) {
        //watch vars in here
    }

    return {
        restrict: 'E',
        scope: {
            companyId: '=companyId'
        },
        bindToController: true,
        templateUrl: 'components/temp/album.tmpl.html',
        controller: 'AlbumController',
        controllerAs: 'albumCtrl',
        link: albumLink
    };
}

})();

模板( album.tmpl.html

 <div ng-controller="AlbumController as albumCtrl">
    testVar: {{albumCtrl.testVar}}<BR>
    companyId:{{albumCtrl.companyId}}<BR>
 </div>

用法

<er-album company-id="2"></er-album>

输出

test var: test var initiated
companyId: 

最佳答案

您需要从模板中删除 ng-controller:

<div>
    testVar: {{albumCtrl.testVar}}<BR>
    companyId:{{albumCtrl.companyId}}<BR>
</div>

关于angularjs - 无法在指令模板中使用指令 Controller 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32906164/

相关文章:

javascript - 使用 angularJS 显示密码的最后三个字符

AngularJs ui-scroll 重新加载不起作用

javascript - Angular JS - Ng-Repeat 问题

javascript - 从深层嵌套指令调用父作用域函数

Python 基本嵌套语句和作用域概念

javascript - 使用 jQuery 和 Javascript 的 for 循环内的函数

闭包函数内部 'this' 范围的 Javascript 混淆

javascript - Transclude 删除 tr 和 td 标签?

javascript - 单击外部时隐藏 Angular UI Bootstrap 弹出窗口

javascript - Angular js 的 HTTP 参数传递