最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - different scope for array and angular copy - Stack Overflow

programmeradmin0浏览0评论

It is easier to see the question from this plunkr:

Click on 'Click to add first' and 'Click to add second', then you can click on the 'lock' icon to see some of the items seem to have the same scope (or same ng-model).

and then click on 'Click to add third' this action does an angular.copy, it does not share the same scope with the other 2. Why is that?

How do I separate the scope so that I can have each 'lock' icon only apply on itself, not other items?

It is easier to see the question from this plunkr: http://plnkr.co/edit/EFZCAXWFui0foMbfZkPb?p=preview

Click on 'Click to add first' and 'Click to add second', then you can click on the 'lock' icon to see some of the items seem to have the same scope (or same ng-model).

and then click on 'Click to add third' this action does an angular.copy, it does not share the same scope with the other 2. Why is that?

How do I separate the scope so that I can have each 'lock' icon only apply on itself, not other items?

Share Improve this question asked Jan 18, 2014 at 1:06 Annie CAnnie C 8142 gold badges14 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

In this line:

var row = {"groupname":Math.floor(Math.random() * 9999999) + 1};

you create a new object and you create a reference to this object which is stored in the variable row. You only add this reference (not a copy of the row object) to your arrays, so the elements in both arrays point to the same object.

angular.copy creates a "deep copy" of your array, so all included objects will be copied and the array contains references to these new objects.

If you want to have separate objects, use angular.copy in the clickFirst function to duplicate the object:

var row = {"groupname":Math.floor(Math.random() * 9999999) + 1};
$scope.products1.push(row);
$scope.products2.push(angular.copy(row));
发布评论

评论列表(0)

  1. 暂无评论