具有多个选项的Angular指令

时间:2015-10-29 04:48:31

标签: javascript angularjs angularjs-directive

我刚在http://plnkr.co/8gJdFrEiplMO7FzOq9Sm

创建了一个plunkr示例

我的问题是,为什么我的playerHtml指令没有得到任何输出?

我的播放器指令看起来像这样

app.directive('playerHtml', function() {
  return {
    restrict: 'A',
    scope: {
      player: '=',
      bold: '=',
      wintype: '='
    },
    templateUrl: 'player.html'
  }
});

和模板

<span ng-if="bold == 1" class="playername winner">{{ player.name }} - {{ player.email }} - {{ wintype }}</span>
<span ng-if="bold == 2" class="playername loser">{{ player.name }} - {{ player.email }} - {{ wintype }}</span>

对指令的调用

<span ng-if="game.winner == 1" player-html player="{{ game.player1 }}" bold="1" wintype="{{ game.wintype }}"></span>
<span ng-if="game.winner != 1" player-html player="{{ game.player1 }}" bold="0" wintype="{{ game.wintype }}"></span>

<span ng-if="game.winner == 2" player-html player="{{ game.player2 }}" bold="1" wintype="{{ game.wintype }}"></span>
<span ng-if="game.winner != 2" player-html player="{{ game.player2 }}" bold="0" wintype="{{ game.wintype }}"></span>

2 个答案:

答案 0 :(得分:2)

使用{{}}有错误,你使用双向绑定将数据传递给你的指令,你需要传递一个得到评估的表达式,而不是{{}}。

http://plnkr.co/edit/x3I0PTqA0VZB05pFC3vx?p=preview

&#13;
&#13;
<span ng-if="game.winner == 1" player-html player="game.player1" bold="1" wintype="game.wintype"></span>
<span ng-if="game.winner != 1" player-html player="game.player1" bold="0" wintype="game.wintype"></span>

<span ng-if="game.winner == 2" player-html player="game.player2" bold="1" wintype="game.wintype"></span>
<span ng-if="game.winner != 2" player-html player="game.player2" bold="0" wintype="game.wintype"></span>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

JavaScript错误控制台显示语法错误,内容如下:

p0={&p1=invalid key&p2=2&p3={{ game.player2 }}&p4={ game.player2 }}

当您将对象传递给指令using =时,您可以为Angular提供对象的命名引用,而不是对象本身,因此您不需要将属性包装在{{ }}中。只需直接使用player="game.player1"等。

这是一个带有修改的forked plunker,似乎可以正常运行。