为什么角度范围保持参考?

时间:2015-09-16 01:50:06

标签: javascript angularjs scope

JS

angular.module('bindExample', []).controller('ExampleController', ['$scope', function($scope) {
    $scope.gridFields = {
        id: {
            width: 50
        },
        price: {
            width: 60
        },
    };
    $scope.allData = {
        'one': {
            id: '1234qwe',
            price: 900
        },
        'two': {
            id: 'asdadw',
            price: 1700
        },
        'three': {
            id: '342sdaw',
            price: 1200
        },
    };
    $scope.edit = function(row) {
        console.log(row);
        $scope.buffer = $scope.allData[row];
    }
}]);

HTML

<div ng-app="bindExample">
   <div ng-controller="ExampleController">
      <table>
         <tbody>
            <tr ng-repeat="(row, data) in allData">
               <td ng-repeat="(field, option) in gridFields" ng-bind="data[field]"></td>
               <td><button ng-click="edit(row)">edit</button></td>
            </tr>
         </tbody>
      </table>
      <div>
         <input type='text' ng-model="buffer.id"/>
      </div>
      <div>
         <input type='text' ng-model="buffer.price"/>
      </div>
   </div>
</div>

点击编辑后,值从$ scope.allData转到$ scope.buffer变量,输入使用缓冲区作为模型,但是当输入改变时,allData变量中的值也会改变,但我不会想要这个,这就是为什么尝试将值传递给其他人......

此处说明的问题:JSFIDDLE

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

使用angular.copy()

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


for(int i=0; i<[tableView numberOfRowsInSection:0]; i++){
    NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:index];

    if(index.row == indexPath.row){
        NSLog(@"select");
    }else{
        NSLog(@"not select");
    } 
} 

答案 1 :(得分:2)

首先,如果您使用父ng-repeat字面而不是数组(Angular并不保证它将按顺序迭代键),您将在object中获得意外结果:< / p>

$scope.allData = [ //you're better off using an Array
            'one': {
                id: '1234qwe',
                price: 900
            },
            'two': {
                id: 'asdadw',
                price: 1700
            },
            'three': {
                id: '342sdaw',
                price: 1200
            },
        ]; //see above

其次,发生这种情况的原因是Javascript将所有内容复制为引用,除非它是原语,所以当你这样做时:

$scope.buffer = $scope.allData[row];

您实际上只是在$scope.allData[row]中存储指向原始对象$scope.buffer的指针。

要做一个“深层复制”你可以按照@ moncefHassein-bey的回答使用angular.copy。

答案 2 :(得分:2)

如果分配的数据为objectarray$scope.buffer = angular.copy($scope.allData[row]); ,则Javascript将保留引用。

它以多种方式为开发人员提供了极大的好处。但如果你想删除引用,你必须克隆它。

使用角度

(text|application)\/(x-)?javascript