Toby Clench Toby Clench - 4 months ago 11
HTML Question

How to set value of span within an Ng-repeat

I am using an ng-repeat in order to list the contents of my data model where the content is being displayed correctly. However, as I am creating a contacts application, I am utilising a circle shape with text inside of it to display the first character from the first name and the first character from the last name, of each contact in the list - my code for this can be seen below:

HTML:

<ul class="collection" ng-show="customers.length">
<li class="collection-item avatar" ng-click="showUserDetail(customer.id)" ng-repeat="customer in customers | orderBy: 'first_name' | filter: searchText" ng-class="{'active': customer.id == selectedUser.id}">
<span ng-init="setContactCircle(customer.first_name,customer.last_name)" id="contact-info" class="contact-circle">TC</span>
<span class="title">{{customer.first_name}} {{customer.last_name}}</span>
<p>{{customer.email}}
<br> {{customer.mobile_number}}
</p>
</li>
</ul>


JS:

$scope.setContactCircle = function(first_name,last_name) {
var strFirst = first_name.charAt(0);
var strLast = last_name.charAt(0);
var strName = strFirst + strLast;

/* span = document.getElementById("contact-info");
txt = document.createTextNode(strName);
span.innerHTML = txt.textContent; */

//document.getElementById("contact-info").innerHTML = strName;

$("#contact-info").text(strName);
console.log(strName);
}


The ng-init appears to be working as the first character from the first name and the first character from the last name are being outputted to the console in 'console.log(strName);' but the text is not being set on the span class.

EDIT

Thank you all for your help where the below has resolved the issue.

HTML:

<span ng-bind="setContactCircle(customer)" id="contact-info" class="contact-circle"></span>


JS:

$scope.setContactCircle = function(customer) {
var strFirst = customer.first_name.charAt(0);
var strLast = customer.last_name.charAt(0);
return strFirst + strLast;
}

Answer

You are mixing jquery and angular. Both are attempting to manipulate the DOM and they don't typically play nice together.

Could you please try -

<span ng-bind="setContactCircle(customer)" id="contact-info" class="contact-circle"></span>


$scope.setContactCircle = function(first_name,last_name) {  
    var strFirst = first_name.charAt(0);
    var strLast = last_name.charAt(0);
    return strFirst + strLast;
}
Comments