0

Here is a very simple example of what I am trying to do

Athlete.save(athlete,function(result)
{
       $scope.athlete = result.athlete;
});

The issue is that the $scope.athlete variable does not update in my view. In order to get it to update I have to do this

Athlete.save(athlete,function(result)
{
       $scope.athlete.fname = result.athlete.fname;
       $scope.athlete.lname= result.athlete.lname;
       $scope.athlete.gender= result.athlete.gender;
       ....
});

This gets annoying very quickly. With the first block of code it's as if angular does not know that my $scope.athlete variable has been updated. This function is triggered from an ng-click, not some jquery call, I am doing it the angular way as far as I know.

here is a simpler case I made: http://plnkr.co/edit/lMCPbzqDOoa5K4GXGhCp

4

3 回答 3

1

athlete = { fname: 'new fname', lname: 'new lname' };似乎正在创建一个名为 的新局部变量athlete,而不是更新您传递的变量。

处理此问题的更好方法是将 的 传递$indexathlete函数updateAthlete()并执行以下操作:

$scope.updateAthlete = function (index) {
    $scope.athletes[index] = { 
      fname: 'new fname', 
      lname: 'new lname'
    };
};

编辑:见工作 plunkr:http ://plnkr.co/edit/KPu3CSvGIl8l581r9A5o?p=preview

于 2013-10-28T04:18:30.517 回答
0

看到这个答案:

https://stackoverflow.com/a/13104500/151084

基元通过值传递,对象通过“引用的副本”传递。

具体来说,当您传递一个对象(或数组)时,您(无形地)传递了对该对象的引用,并且可以修改该对象的内容,但是如果您尝试覆盖引用,则不会影响调用者持有的引用 - 即引用本身是按值传递的。

这解释了为什么 plunker 不更新。但是,您的内联代码示例(您使用的地方$scope.athlete = result.athlete)似乎应该可以工作。你能创建一个显示失败的样本吗?

于 2013-10-28T04:44:09.867 回答
0

我从这里得到帮助来解决这个问题:https ://groups.google.com/forum/#!msg/angular/Ih06VLDH_JU/EtHLrGeMgUEJ

有两种方式,一种是前面已经提到过,什么是使用索引来更新原来的方式。

第二种方法是使用 angular.copy(source, destination)

于 2013-10-29T03:49:58.010 回答