Martin-
Martin-

Reputation: 927

Angular directive with multiple options

I just created a plunkr example at http://plnkr.co/8gJdFrEiplMO7FzOq9Sm

My question is, why does my playerHtml directive not getting any output?

My player directive looks like this

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

And the template

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

And the call to the directive

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

Upvotes: 0

Views: 32

Answers (2)

Kristj&#225;n
Kristj&#225;n

Reputation: 18813

The JavaScript error console is showing a syntax error that reads:

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

When you pass objects to a directive using =, you give Angular the named reference to the objects, not the objects themselves, so you don't need to wrap your attributes in {{ }}. Just use player="game.player1", etc., directly.

Here's a forked plunker with the modification, which appears to run correctly.

Upvotes: 1

Leandro Zubrezki
Leandro Zubrezki

Reputation: 1150

Using {{}} there is wrong, you are using two-way binding for passing data to your directive, you need to pass an expression that gets evaluated, without {{}}.

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

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

Upvotes: 2

Related Questions