来自指令的数据不在ng-repeat中显示

时间:2013-12-16 11:45:50

标签: javascript angularjs angularjs-directive

我把这个问题分解成最简单的形式。基本上我有一个指令,对于演示,还没有真正做任何事情。我有一个div作为属性的指令。 div中的值(来自对象数组)不会显示。如果我从div中删除指令,它们会显示OK。我显然遗漏了一些非常明显的东西,因为我之前没有遇到任何问题。

这是Plunk:http://plnkr.co/edit/ZUXD4qW5hXvB7y9RG6sB?p=preview

脚本:

app.controller('MainCtrl', function($scope) {

  $scope.tooltips = [{"id":1,"warn":true},{"id":2,"warn":false},{"id":3,"warn":true},{"id":4,"warn":true}];

});

app.directive("cmTooltip", function () {
    return {
        scope: {
            cmTooltip: "="
        }
    };
});

HTML

<div ng-repeat="tip in tooltips" class="titlecell" cm-tooltip="true">
    A div element: {{ tip.id }}
</div>
<br><br>

Just to prove it works without the directive:
<div ng-repeat="tip in tooltips" class="titlecell">
    A div element: {{ tip.id }}
</div>

3 个答案:

答案 0 :(得分:1)

正如Beyers上面和下面的评论一样,问题的行为至少不再存在于1.2.5

更清楚;这个与ng-repeat 无关,你可以删除它,但仍然没有tip(或tooltips)。

请参阅this关于=和其他配置意味着什么以及它为您做了什么的问题。

基本上对于您使用=时的情况,指令的范围将用于底层元素,您不再拥有控制器的范围。这对您来说意味着没有{{ tip.id }}甚至没有tip。因为该指令不提供。

这是一个plunker,展示了你可以用它做什么。

基本上我所做的只是

app.directive("cmTooltip", function () {
    return {
        scope: {
            cmTooltip: "="
        },
        link: function($scope){    // <<
          $scope.tip = { id: 1 };  // <<
        }                          // <<
    };
});

这会在作用域上创建tip对象,因此它具有id。

根据您的情况,您可能不会使用=并根据您的需要查看this问题以获取其他选项。

答案 1 :(得分:1)

有一个 hack 通过使用transclusion使其在早期版本的角度中工作,就像那样:

app.directive("cmTooltip", function () {
    return {
        scope: {
           cmTooltip: "="
        },
        transclude:  true,
        template : '<div ng-transclude></div>'
    };
});

PLNKR

答案 2 :(得分:-2)

在我看来,这不是要走的路。 我会使用Objects。

JS代码:

  function tooltip(id,warn){
    this.id = id;
    this.warn = warn;
  }

  tooltip.prototype.toString = function toolToString(){
    return "I'm a tooltip, my id = "+this.id+" and my warn value = "+this.warn;
  }

  $scope.tooltips = [new tooltip(1,true),new tooltip(2,false),new tooltip(3,true),new tooltip(4,true)];

HTML:

<div ng-repeat="tip in tooltips" class="titlecell">
        A div element: {{ tip.toString() }}
    </div>
相关问题