用ng变化更新角度模型

Updating angular model with ng-change

本文关键字:模型 更新 ng 变化      更新时间:2023-09-26

我的目标很简单,就是在用JQuery更新了绑定的模型的值之后,也能够更新它。我正在使用一些相当固定的遗留代码,所以我真的不能用老式的有角度的方式来完成它(见下文)。

非常重要:我无法使用选择字段上的ng repeat,ng选项。选项的值与相应的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);

控制器功能:

// I know this part is for sure wrong.. really needs help
$scope.forceApply = function(applymodel){
   $scope.$apply(applymodel);
}

您可以为此创建一个自定义指令:

角度

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>

plunkr:http://plnkr.co/edit/Z8tWQHDJWtPN6Yrjwu3a?p=preview