【问题标题】:Angular - Trying to sync two drop downsAngular - 尝试同步两个下拉菜单
【发布时间】:2017-03-01 22:51:08
【问题描述】:

我正在尝试在 Angular 1.4.7 中同步两个下拉菜单,以便在更新一个下拉菜单时将另一个下拉菜单设置为相同的值,反之亦然。似乎我关闭了,但不是被同步,而是另一个下拉更改为默认的“选择”值。

这是我正在处理的网站上的问题的简化版本。有问题的网站是非常数据驱动的,所以我希望让它在这个结构中工作。也就是说,一个 inputData 对象数组,每个对象都包含月份数组和一个 selectedMonth 属性。

应用程序运行良好,除了这个新要求。我错过了什么?

我包含了源代码和显示问题的 plunker。

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"];
    }

}]);

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    不确定你打算在这里做什么

    currInput.selectedMonth=$.extend({}, selectedInput.selectedMonth);

    我将其更改为以下内容,并且可以正常同步。

    currInput.selectedMonth=selectedInput.selectedMonth;
    

    这里是working plnkr

    【讨论】:

      【解决方案2】:

      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

      【讨论】:

        【解决方案3】:

        在 ng-repeat 中,每个实例都有自己的作用域。尝试在ng-model 中使用$parent.input.selectedMonth

        【讨论】:

          猜你喜欢
          • 2021-09-06
          • 1970-01-01
          • 2015-09-30
          • 1970-01-01
          • 2016-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多