Search code examples
angularjsangularjs-components

Angular JS controller property not evaluated


I have a component with a controller and template. Properties from the controller are being replaced in the template when they are between html tags, but not as tag attributes.

So given this component:

  angular.module('OeApp').component('phonemeComponent', {
    templateUrl: '/src/templates/phoneme.template.html',
    controller: 'PhonemeController as ctrl',
    bindings: {
      exercise: '<'
    }
  })

Controller:

angular.module('OeApp').controller('PhonemeController', PhonemeController);

function PhonemeController() {
  var ctrl = this;

  ctrl.listenButtonUrl = "/images/speaker-button-sm.gif"; 
};

Template snippet:

<div id="phoneticSymbol">{{ctrl.exercise.phoneticSymbol}}</div>

<!-- sample word -->
<img class="listenButton" src="ctrl.listenButtonUrl"></img>

<div id="oeWord">{{ctrl.exercise.sampleWordOE}}</div>
<div id="modWord">({{ctrl.exercise.sampleWordModE}})</div>

The phoneticSymbol, oeWord, and modWord are all replaced as expected, but src for the img is the literal string "ctrl.listenButtonUrl". What am I missing?

I tried enclosing ctrl.listenButtonUrl in curly braces, even though that's not how it works in other sample code, and the browser first tries to resolve the literal string as a url (resulting in a 404), but eventually gets the right value, so I don't think that's the right solution.


Solution

  • You need to use ng-src

    <img class="listenButton" ng-src="{{ctrl.listenButtonUrl}}"></img>