不能在指令模板中使用指令控制器值

时间:2015-10-02 11:26:27

标签: angularjs angularjs-directive scope attributes

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

指令+指令控制器

(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: 

2 个答案:

答案 0 :(得分:4)

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

[Fact]
public void TestEquivalentSequences()
{
    var foos = new[]
    {
        new Foo { Number = 42, Text = "ploeh" },
        new Foo { Number = 1337, Text = "fnaah" }
    };
    var bars = new[]
    {
        new Bar { Number = 42, Text = "ploeh" },
        new Bar { Number = 1337, Text = "fnaah" }
    };

    AutoMapper.Mapper.CreateMap<Foo, Bar>();

    Assert.True(
        foos.Select(AutoMapper.Mapper.Map<Bar>).SequenceEqual(
            bars,
            new SemanticComparer<Bar>()),
        "Mapped arrays should be equivalent.");
}

答案 1 :(得分:0)

为了达到您想要的结果,我必须稍微修改代码的结构。希望这有助于您了解问题。查找Angular与指令一起使用的隔离范围的材料。

HTML:

<div ng-app="erCommon" ng-controller="AlbumController as albumCtrl">
  <er-album company-id="2" test = "albumCtrl.testVar"></er-album>
</div>

控制器:

angular.module('erCommon', [])
    .directive('erAlbum', albumDirective)
    .controller('AlbumController', AlbumController);

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

function albumDirective() {
    return {
        restrict: 'E',
        scope: {
            test: '=test',
            companyId: '@companyId'
        },
        template: '<div> testVar: {{test}}<BR> companyId:{{companyId}}<BR> </div>', // it will work fine with templateUrl as well, just didn't want to cr8 another file...
        link: function(scope, element, attrs){
          //do whatever else you might need;
        }
    };
}