Robin Robin - 4 months ago 13
HTML Question

ng-repeat not working , when used in <li> tag

span
is not displayed but the button in the
li
tag is being displayed if
ng-repeat
is not used , but once i use
ng-repeat
, neither the
span
nor the button is being displayed.
I have used
ng-repeat
numerous times but never faced such a situation, both
span
and button elements are not displayed if I use
ng-repeat
in the
li
tag.

This is the index.html file:

<ul id="contactdelete">
<li ng-repeat="contact in $ctrl.contacts">
<span>{{contact.name}}</span>
<button ng-click="$ctrl.deletecontact()">Delete</button>
</li>
</ul>


This is the controller.js file

(function() {

class ContactsComponent {
constructor($http) {

var result;

$http.get("/api/contacts/").success(function(response) {

result = response;

});

this.contacts = result;
}
}

angular.module('myApp')
.component('contacts', {
templateUrl: 'app/contacts/contacts.html',
controller: ContactsComponent
});
})();

Answer

this.contacts is empty as the success callback is async and its context is different from the constructor, which is why you can't use this directly.

Also, you should use the then function which takes 2 functions as arguments, one for success, the other as an error callback.

One way to work around this is making this a local variable, then using it inside the callback.

var self = this;
$http.get("/api/contacts/").then(function(response){

    self.contacts = response; // or response.data, depending of what you're receiving.

});

Or you could use the bind function:

$http.get("/api/contacts/").then(function(response){
    this.contacts = response; 

}.bind(this)); // notice the bind here

Angular provides its own bind implementation:

$http.get("/api/contacts/").then(angular.bind(this, function(response){

    this.contacts = response;

}));