Change value of copy's scope 改变范围的值
Change value of copy's scope change value of scope
我不明白为什么要更改副本的值,更改 $scope 的值:
var tmpmember = $scope.registration.member;
console.log($scope.registration.member.birth);
tmpmember.birth=$filter('date')($scope.registration.member.birth,'yyyy-MM-dd');
console.log(tmpmember.birth);
console.log($scope.registration.member.birth);
输出:
Thu Mar 11 1954 01:00:00 GMT+0100 (CET)
261 1954-03-11
262 1954-03-11
有人可以给我解释一下吗?
非常感谢
在您提供的代码中,您没有复制对象。相反,您创建了指向同一对象实例的第二个变量。
Angular 有一个功能可以使用,如果你真的希望有一个副本而不是额外的参考,angular.copy
。 https://docs.angularjs.org/api/ng/function/angular.copy#!/
var tmpmember = angular.copy($scope.registration.member);
console.log($scope.registration.member.birth);
tmpmember.birth = $filter('date')($scope.registration.member.birth, 'yyyy-MM-dd');
console.log(tmpmember.birth);
console.log($scope.registration.member.birth);
结果:
Thu Mar 11 1954 01:00:00 GMT+0100 (CET)
261 1954-03-11
Thu Mar 11 1954 01:00:00 GMT+0100 (CET)
我不明白为什么要更改副本的值,更改 $scope 的值:
var tmpmember = $scope.registration.member;
console.log($scope.registration.member.birth);
tmpmember.birth=$filter('date')($scope.registration.member.birth,'yyyy-MM-dd');
console.log(tmpmember.birth);
console.log($scope.registration.member.birth);
输出:
Thu Mar 11 1954 01:00:00 GMT+0100 (CET)
261 1954-03-11
262 1954-03-11
有人可以给我解释一下吗?
非常感谢
在您提供的代码中,您没有复制对象。相反,您创建了指向同一对象实例的第二个变量。
Angular 有一个功能可以使用,如果你真的希望有一个副本而不是额外的参考,angular.copy
。 https://docs.angularjs.org/api/ng/function/angular.copy#!/
var tmpmember = angular.copy($scope.registration.member);
console.log($scope.registration.member.birth);
tmpmember.birth = $filter('date')($scope.registration.member.birth, 'yyyy-MM-dd');
console.log(tmpmember.birth);
console.log($scope.registration.member.birth);
结果:
Thu Mar 11 1954 01:00:00 GMT+0100 (CET)
261 1954-03-11
Thu Mar 11 1954 01:00:00 GMT+0100 (CET)