Javascript ng在<;中使用时,重复不工作;李>;标签

Javascript ng在<;中使用时,重复不工作;李>;标签,javascript,html,angularjs,Javascript,Html,Angularjs,如果未使用ng repeat,则不会显示span,但会显示li标记中的按钮,但一旦使用ng repeat,则不会显示span或按钮。 我曾多次使用ng repeat,但从未遇到过这种情况,如果在li标记中使用ng repeat,则span和按钮元素都不会显示 这是index.html文件: <ul id="contactdelete"> <li ng-repeat="contact in $ctrl.contacts"> <span>{

如果未使用
ng repeat
,则不会显示
span
,但会显示
li
标记中的按钮,但一旦使用
ng repeat
,则不会显示
span
或按钮。 我曾多次使用
ng repeat
,但从未遇到过这种情况,如果在
li
标记中使用
ng repeat
,则
span
和按钮元素都不会显示

这是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>

您应该移动
this.contacts=result到内部成功函数:

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

     result = response;
     this.contacts = result;

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

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

我认为你必须使用
result=response.data
而不是
result=response

这个。联系人是空的,因为
success
回调是异步的,它的上下文与构造函数不同,这就是为什么你不能直接使用
this

另外,您应该使用函数,该函数接受两个函数作为参数,一个用于成功,另一个作为错误回调

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

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

});
解决此问题的一种方法是将
this
设置为局部变量,然后在回调中使用它

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

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

});
或者您可以使用以下功能:

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

     result = response;
     this.contacts = result;

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

}.bind(this)); // notice the bind here
Angular提供了自己的实现:

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

    this.contacts = response;

}));
关于范围和上下文的其他信息:


您是否尝试了
结果=响应。数据
?当您使用
控制台。日志(响应)
时,您得到了什么?谢谢!。。。。但在很多情况下,我使用了“this”关键字。例如,在html文件中使用ng model=“$ctrl.logo”时,我在js文件中使用此关键字作为logo,但为什么我不能使用几个月来一直使用的相同语法,而为什么我要再次创建一个名为self的东西呢?
this
关键字指的是最内部函数的上下文。回调有自己的上下文,而不是控制器构造函数的上下文。如果是内联定义的,则可以从回调中访问局部变量,但
值将更改。您可以使用或
apply
注入调用函数的上下文。要覆盖回调的上下文并确保
是您想要的,您可以使用
bind
作为我的第二个示例。您能推荐一个源代码吗,我可以在那里详细了解这一点!我在答案的末尾添加了链接