1

I am trying to make custom directive to display:

Will {{selectedAsset}} go {{red}} or {{green}}?

It looks like this on the screen:

AUD/USD will down(red color) or up(green color)?

The {{red}} and {{green}} part should have its own color . Hence I am trying to wrap it with a span having desired classes.

But it is not working, below is the code:

<trade-header selected-asset="selectedAsset" red="widgetMessage.goDown" green="widgetMessage.goUp"></trade-header>

var widgetMessage = {
    "Trade_Header": "Will {{selectedAsset}} go {{red}} or {{green}}?",
    "goUp": "up",
    "goDown": "down"}

myApp.directive("tradeHeader", function($sce) {
    return {
        restrict: "AE",
        scope: {
            selectedAsset: "=",
            green:"=",
            red:"="
        },
        link: function(scope, element, attrs) {
            scope.green = $sce.trustAsHtml('<span class="goOrDonwLabel upGreen">' + scope.green + '</span>');
        },
        template: widgetMessage.Trade_Header,
    }
});

widgetMessage.Trade_Header need to be variable cause the design.

This consequence will be : "AUD/USD will down or <span class="Green">up</span>?"

I need it to be compiled as HTML, any suggestions?

Sing
  • 3,942
  • 3
  • 29
  • 40

1 Answers1

0

Your html should be in the template. When you're trying to manipulate HTML in code, that's usually a sign you're not using templates the right way. Try something like this:

<trade-header selected-asset="selectedAsset" red="widgetMessage.goDown" green="widgetMessage.goUp"></trade-header>


var widgetMessage = {
"Trade_Header": 'Will {{selectedAsset}} go {{red}} or <span ng-class="greenLabel">{{green}}</span>?',
"goUp": "up",
"goDown": "down"}

myApp.directive("tradeHeader", function($sce) {
return {
    restrict: "AE",
    scope: {
        selectedAsset: "=",
        green:"=",
        red:"="
    },
    link: function(scope, element, attrs) {
        scope.greenLabel = widgetMessage.goUp; // logic for setting green's class here
    },
    template: widgetMessage.Trade_Header,
}
});
Kaiden
  • 188
  • 3
  • 8
  • But I think in this way I would have higher cost on maintenance, because I have several similar things... Could it possible compile to html while rendering? – Sing Mar 03 '15 at 10:10
  • Are you just trying to change the styling of the {{red}} and {{green}} sections? If so, you'll want to just dynamically add/remove classes on those elements instead of generating the html. If you're doing something more complicated than that and the structure of the HTML needs to change, than that's a good candidate for pulling out into it's own directive. – Kaiden Mar 04 '15 at 02:17