我的目标非常简单,就是在使用 JQuery 更新其值后,能够更新我也绑定(bind)的模型。我正在使用一些相当固定的遗留代码,所以我不能真正用老式的 Angular 方式来做(见下文)。
非常重要:我无法在选择字段上使用 ng-repeat、ng-options。选项的值与相应的 ID 相关联——我无法更改该数据的格式。如有必要,我可以向这些元素添加新指令。我提前对这些限制表示歉意..
这是我现在拥有的:
HTML
<select id="animalSelection" ng-change="forceApply(my.animal)">
<option value="1">Dog</option>
<option value="2">Cat</option>
<option value="3">Zebra</option>
</select>
<input type="hidden" id="animalSelected" ng-model="my.animal" />
<h1>Selected Animal: {{my.animal}}</h1>
JS
// Get text of selected option
var animal = $("#animalSelection option:selected").text();
// Updates hidden input with ng-model attribute
$("#animalSelected").val(animal);
Controller 功能:
// I know this part is for sure wrong.. really needs help
$scope.forceApply = function(applymodel){
$scope.$apply(applymodel);
}
最佳答案
您可以为此创建自定义指令:
Angular
app.directive('myChange', function () {
return {
restrict: 'A',
scope: {
//the ng-model you want to modify
myModel: '='
},
link: function (scope, ele) {
// sets first value on load
scope.myModel = ele.find(':first').text();
ele.bind('change', function () {
// applies scope change
scope.myModel = ele.find(':selected').text();
scope.$apply();
});
}
}
});
html
<select id="animalSelection" data-my-model="my.animal" data-my-change>
<option value="1">Dog</option>
<option value="2">Cat</option>
<option value="3">Zebra</option>
</select>
<input type="hidden" id="animalSelected" ng-model="my.animal" />
<h1>Selected Animal: {{my.animal}}</h1>
关于javascript - 使用 ng-change 更新 Angular 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26790605/