Reputation: 1124
I have an Angular partial page containing a form. In one of the input headings I want to show the currency based on the country selected. The currency symbol is in a span inside a JSON string that is loaded by angular-translate. On page load of the partial, no currency symbol appears in the input heading. If the user changes the country, the currency symbol for that country appears in the heading. Its some timing issue on the following relevant code:
HTML
<label for="price" translate>PRICE</label>
<input type="text" id="price" name="price" data-ng-model="cntrl.input.price" size="12" maxlength="12" />
JSON string for the English translation
"PRICE": "Price <span id='currencySymbol'></span><span class='required'>(Required)</span>"
Angular controller - using John Papa's style guide for controller as
function InputFormController( $translate, $translatePartialLoader, selectCountryTranslateFactory, $timeout, $scope ) {
var cntrl = this;
cntrl.input = {};
//set country in select tag for page load
cntrl.input.countrySelected = "US";
$scope.$watch( "cntrl.input.countrySelected", function( newVal, oldVal ) {
setCurrencySymbol( cntrl.input.countrySelected ); //TEST
});
function setCurrencySymbol() { //TEST
var targetSpan = document.getElementById( "currencySymbol" );
switch ( cntrl.input.countrySelected ) {
case 'US':
targetSpan.innerHTML = " $"; //Error: targetSpan is null - on page load, but displays symbol after user selects a different country
break;
case 'CA':
targetSpan.innerHTML = " C$";
break;
default:
//show no symbol
targetSpan.innerHTML = "";
break;
}
}
To be clear, I get Price (Required) on page load with US as the default country. If I change to Canada, I get Price C$ (Required) If I change back to US, I get Price $ (Required)
I'm using Angular 1.3.7 How does one get the span to load after angular-translate loads - or is there some other approach for making the setCurrencySymbol function?
Upvotes: 0
Views: 156
Reputation: 1124
I believe the core of this problem is in AngularJS, but I do not have the skill to fix it (or prove that it is a bug). I took a different approach and removed the currencySymbol span from the translate JSON string. I added a second label tag to the input box. I thought this was a cludge, but to my surprise it W3C validates as error-free HTML. Multiple labels are OK. So after removing the span, a single line of HTML changes and it works.
<label for="monthlyRental" id="currencySymbol" class="boldHeading"></label><label for="monthlyRental" class="boldHeading" translate>PRICE</label>
On page load, I now get $ Price (Required). The currency symbol changes as the user selects a different country. The currency symbol could also be placed at the end of the heading by changing the order of the labels. But this approach will not put the currency symbol in the middle of that string. Some very deep knowledge of AngularJS is necessary for that.
Upvotes: 0