Angular指令 - 隔离范围不显示

时间:2015-10-31 13:59:56

标签: javascript angularjs angularjs-directive angularjs-scope

我试图制作一个接受属性并将其挂钩到隔离范围的指令,但是属性值没有显示。

angular.module('app', [])
.controller('torrentController', [function() {
    this.recommended = ['...'],
    this.otherArray = ['...']
}])
.directive('torrentsTable', [function() {
    return {
        restrict: 'E',
        templateUrl: 'templates/directives/torrentsTable.html',
        scope: {
            index: '='
        },
        controller: 'torrentController as torrentCtrl'
    };
}]);

我们的想法是使用此指令以这种语法显示不同的种子列表:

<torrents-table index="recommended"></torrents-table>
<torrents-table index="someOtherIndex"></torrents-table>

我希望这2条几乎相同的行显示不同的&#34; list&#34;结果。

templates/directives/torrentsTable.html

<!-- I also tried with ng-repeat="torrent in torrentCtrl.recommended" -->
<!-- And is working as I excepted (It's shows the recommended array) -->

<div layout="row" ng-repeat="torrent in torrentCtrl[index]">
    <div flex>Name: {{torrent.name}}</div>
    <div flex>{{index}}</div>
</div>

{{index}}未显示,且其值未显示 虽然我实际上制作了硬编码的ng-repeat参数 - 但它重复但{{index}}是空的。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的问题:如何传递密钥。

您在指令中使用:

scope: {
    index: '='
},

所以你应该传递给指向表达式,它被评估为$scope属性。因此,如果您不注入范围 - 您传递 undefined

您可以通过以下两种方式解决问题:
1)传递字符串而不是其他东西

<torrents-table index="'recommended'"></torrents-table>
<torrents-table index="'someOtherIndex'"></torrents-table> 

2)将指令定义更改为

scope: {
    index: '@'
},
您可以在下面的代码段中看到

示例。

angular.module('app', [])
.controller('torrentController', [function() {
    this.recommended = [1,2,3,4,5];
    this.someOtherIndex = ['a','b','c','d','e'];
}])
.directive('torrentsTable', [function() {
    return {
        restrict: 'E',
        template: '<div flex>{{index}}</div>'+
                  '<div layout="row" ng-repeat="torrent in torrentCtrl[index]">'+
                  '  <div flex>Name: {{torrent}}</div>'+
                  '</div>',
        scope: {
            index: '='
        },
        controller: 'torrentController as torrentCtrl'
    };
}])
.directive('torrentsTable2', [function() {
    return {
        restrict: 'E',
        template: '<div flex>{{index}}</div>'+
                  '<div layout="row" ng-repeat="torrent in torrentCtrl[index]">'+
                  '  <div flex>Name: {{torrent}}</div>'+
                  '</div>',
        scope: {
            index: '@'
        },
        controller: 'torrentController as torrentCtrl'
    };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-app='app'>
  <torrents-table index="'recommended'"></torrents-table>
  <torrents-table index="'someOtherIndex'"></torrents-table>  
  <hr/>
  <torrents-table2 index="recommended"></torrents-table2>
  <torrents-table2 index="someOtherIndex"></torrents-table2>  
</div>

相关问题