span
不会显示,但如果不使用 ng-repeat
,则会显示 li
标记中的按钮,但是一旦我使用ng-repeat
, span
和按钮都没有显示。
我曾多次使用 ng-repeat ,但从未遇到过这种情况,如果我使用 ng-repeat ,则 span
和按钮元素都不会显示在 li
标签中。
这是index.html文件:
<ul id="contactdelete">
<li ng-repeat="contact in $ctrl.contacts">
<span>{{contact.name}}</span>
<button ng-click="$ctrl.deletecontact()">Delete</button>
</li>
</ul>
这是controller.js文件
(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
});
})();
最佳答案
this.contacts
为空,因为 success
回调是异步的,并且其上下文与构造函数不同,这就是为什么您不能使用 this
直接。
此外,您应该使用 then
函数接受 2 个函数作为参数,一个表示成功,另一个作为错误回调。
解决此问题的一种方法是将 this
设为局部变量,然后在回调中使用它。
var self = this;
$http.get("/api/contacts/").then(function(response){
self.contacts = response; // or response.data, depending of what you're receiving.
});
或者您可以使用 bind
功能:
$http.get("/api/contacts/").then(function(response){
this.contacts = response;
}.bind(this)); // notice the bind here
Angular 提供了自己的 bind
实现:
$http.get("/api/contacts/").then(angular.bind(this, function(response){
this.contacts = response;
}));
有关范围和背景的其他信息:
关于javascript - 在 <li> 标记中使用时,ng-repeat 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510283/