2017-03-01 37 views
2

我試圖在Angular 1.4.7中同步兩個下拉,這樣當一個下拉更新時,另一個下拉被設置爲相同的值,反之亦然。看起來像im close,但不是同步,另一個下拉更改爲默認的「選擇」值。角度 - 試圖同步兩個下拉

這是我正在研究的網站上的問題的簡化版本。有問題的網站是非常數據驅動的,所以我希望能夠在這個結構中使用它。也就是說,一組inputData對象,每個對象都包含一個selectedMonth屬性的月數組&。

該應用程序工作正常,除了這個新的要求。我錯過了什麼?

我收錄了源代碼和一個顯示問題的插頁。

https://plnkr.co/edit/wSsBO4dHP0SR6HliP0b8?p=preview

HTML

<div class="form-group" ng-repeat="input in inputData"> 

    <select name="inputMonth__{$index}}" id="inputMonth__ID_{{$index}}" 
      ng-model="input.selectedMonth" 
      ng-change="option_changed(input)" 
      ng-options="month as month for month in input.Months " > 
     <option value="" style="display:none">Select</option> 
    </select> 
    <br><br> 

</div> 

控制器 - test.js

'use strict'; 

var app = angular.module('app',[]); 

app.controller('testController', ['$scope', function ($scope) { 


    $scope.inputData=[]; 
    $scope.inputData.push(new inputData()); 
    $scope.inputData.push(new inputData()); 


    $scope.option_changed = function(Input) { 

     SyncDropdowns(Input) 


    }; 

     function SyncDropdowns(selectedInput){ 


      for(var i = 0; i < $scope.inputData.length ; i++) { 

       var currInput=$scope.inputData[i]; 
       if (currInput!=selectedInput){ 
        currInput.selectedMonth=$.extend({}, selectedInput.selectedMonth); 

       } 
      } 
    } 


    function inputData(){ 
     this.selectedMonth={}; 
     this.Months=["April", "May", "June", "July"]; 
    } 

}]); 

回答

3

不知道你打算用

currInput.selectedMonth = $這裏做什麼擴展({}, selectedInput.selectedMonth);

我將其改爲簡單以下,它同步罰款。

currInput.selectedMonth=selectedInput.selectedMonth; 

這裏是working plnkr

0

jQuery的延長

$.extend({},"June") 

回報

{ 
    "0": "J", 
    "1": "u", 
    "2": "n", 
    "3": "e" 
} 

更新此功能

function SyncDropdowns (selectedInput) { 
    for(var i = 0; i < $scope.inputData.length ; i++) { 
     var currInput=$scope.inputData[i]; 
     if (currInput!=selectedInput){ 
      currInput.selectedMonth=selectedInput.selectedMonth; 
     } 
    } 
} 

updated plnkr

0

ng-repeat中的每個實例都有自己的作用域。嘗試在ng-model中使用$parent.input.selectedMonth