2014-11-06 94 views
2

我的目標很簡單,就是能夠更新我綁定的模型,並在使用JQuery更新其值之後進行綁定。我正在使用一些相當固定的遺留代碼,所以我不能真正做到這一點老式的角度(見下文)。使用ng-change更新角度模型

非常重要:我沒有能力在選擇字段上使用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); 

控制器功能:

// I know this part is for sure wrong.. really needs help 

$scope.forceApply = function(applymodel){ 
    $scope.$apply(applymodel); 
} 

回答

2

您可以創建這個自定義指令:

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

+0

這樣做!你是我個人的耶穌。 – 2014-11-07 03:29:27