1

I am trying to do a function inside of a controller that uses an if else to change the return. And it works until I change the drop down, and then stops working completely. It does not seem to be working, not sure if I am doing something wrong, or you just cannot do this type of function. Any help would be appreciated.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-sanitize.js"></script>

<script>
    var app = angular.module('newApp', ['ngSanitize']);
    app.controller('player1ctrl', function ($scope) {
        $scope.playerName = "Hero";
        $scope.playerCard = "A<br />&spades;";
        $scope.color = function () {
            //return $scope.playerName;
            var arr = $scope.playerCard.split("<br />");
            var rtn = "";
            if (arr[1] == "&spades;" || arr[1] == "&clubs;") {
                return "Black";
            }
            else {
                return "Red";
            }
        };
    });
</script>



<title>test ngbindhtml</title>
<meta charset="utf-8" />
</head>
<body ng-app="newApp">
<div ng-controller="player1ctrl">
    Card selected: <p ng-bind-html="playerCard"></p>
    Suit Color: {{color()}}
    <select name="playerCard" ng-model="playerCard">
        <option value="2&lt;br /&gt; &amp;spades;">2 &spades;</option>
        <option value="3&lt;br /&gt; &amp;spades;">3 &spades;</option>
        <option value="4&lt;br /&gt; &amp;hearts;">4 &hearts;</option>

     </select>
</div>
</body>
</html>
Kuroi
  • 212
  • 2
  • 15
AVRnj
  • 11
  • 3

2 Answers2

0

First of all - You have space in &spades;:

if(arr[1] == " &spades;" || arr[1] == " &clubs;")

Second - You need use:

ng-bind-html-unsafe="playerCard"

in Your template or use trustAsHtml in controller;
Plunker

Community
  • 1
  • 1
user3335966
  • 2,673
  • 4
  • 30
  • 33
0

You cannot bind an HTML string without "trusting" it in Angular. Your "playerCard" variable, with the <br /> is causing the issue. You need to inject $sce into your controller and then call the trustAsHtml function:

...
app.controller('player1ctrl', function ($scope, $sce) {
...
$scope.playerCard = $sce.trustAHtml("A<br />&spades;");

Doing this should allow you to still use [the correct] ng-bind-html like you currently are. You can also turn this into a directive quite easily.

Scott Byers
  • 3,007
  • 2
  • 17
  • 14
  • Guys, thanks for the replies! The html is not the problem, that is working fine for me, as the ngsantizie is handling that in this version. The problem was the space, once I fixed that it worked as I hoped. Thanks much! – AVRnj Sep 17 '15 at 13:06