有人可以帮助我理解为什么Lodash在使用findWhere获取对象时做了一个引用副本,它使我能够将整个变量绑定到范围并根据用户操作动态更改它。 但是,使用复制操作完成同样的操作无法更新源对象。我已经把出plunker http://plnkr.co/edit/Phy5xQnGBYsBnenMQHOd?p=preview了解Lodash - 在javascript中寻找并复制运算符
HTML代码:
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker for service response data binding</title>
<script data-require="[email protected]" data-semver="2.4.1" src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" data-ng-model="inputModel" />
<input type="text" data-ng-model="inputModel2.desc" />
<button data-ng-click="btnClick()">Click me and check console</button>
</body>
</html>
JS代码:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope,$http) {
var someServiceResponse = [{"code":"1","desc":"apple"},{"code":"2","desc":"orange"}];
$scope.inputModel = someServiceResponse[0].desc;
$scope.inputModel2 = _.findWhere(someServiceResponse,{'code':'2'});
$scope.btnClick = function(){
console.log($scope.inputModel);//Outputs the changed value in the text box1
console.log($scope.inputModel2.desc);//Outputs the changed value in the text box2
console.log(someServiceResponse[0].desc); // Still shows the old value from the service response - always shows apple
console.log(someServiceResponse[1].desc); // shows updated value from second text box
};
});
对我来说,最后两个console.log始终显示苹果和橙。 – Absor 2014-10-29 21:44:00
吸收 - 道歉!我的错。我已经更新了这个问题以及抢劫犯。 – WiseWins 2014-10-29 22:00:57
inputModel是对字符串的引用,如果更新,则引用将被设置为新字符串。 inputModel2是一个对象的引用,并且你在其中更新了desc字符串。 – Absor 2014-10-29 22:15:29