假设我有这个 Controller :
myApp.controller('testCtrl', function ($scope) {
$scope.cars = [
{ carId: '1', carModel: 'BMW', carOwner: 'Nader' },
{ carId: '2', carModel: 'Mercedes', carOwner: 'Hisham' },
{ carId: '3', carModel: 'Opel', carOwner: 'Saad' }
];
});
和这个 HTML:
<select ng-options="car as car.carModel for car in cars" ng-model="car"></select>
<br />
<label> Car ID </label> <input type="text" ng-model="car.carId" />
<br />
<label> Car Model </label> <input type="text" ng-model="car.carModel" />
<br />
<label> Car Owner </label> <input type="text" ng-model="car.carOwner" />
当用户选择一辆汽车时,它应该自动将所选汽车的值绑定(bind)到文本框,这在本例中已经发生了。但是,当我更改 carModel
文本框中的值时,下拉列表中的 carModel
名称也会更改。
如何在不更改下拉列表中的值的情况下更改 carModel
的输入?请注意,每当用户从下拉列表中选择不同的值时,我想将当前所选汽车的信息绑定(bind)到文本框。
用例
假设从数据库中检索汽车列表,我希望用户编辑所选汽车,所以首先我想在用户从下拉列表中选择汽车信息时显示汽车信息,然后更改他想要的任何内容并调用用于更新所选汽车的网络服务。
最佳答案
您可以为此使用 angular.copy
:
JavaScript: 在你的 testCtrl
中定义 callTest
函数
$scope.cars = [ ... ];
$scope.callTest = function(objCar) {
console.log(objCar);
$scope.carModel = angular.copy(objCar); // this carModel is used in the html
};
HTML:
<select ng-change="callTest(car)" ng-options="car as car.carModel for car in cars" ng-model="car"></select>
<br />
<label> Car ID </label>
<input type="text" ng-model="carModel.carId" />
<br />
<label> Car Model </label>
<input type="text" ng-model="carModel.carModel" />
<br />
<label> Car Owner </label>
<input type="text" ng-model="carModel.carOwner" />
在 Controller 中使用 ng-change 事件
选择并调用 callTest()
函数。
这是 Plunker
关于javascript - 带 Angular 下拉绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35115449/