问题 如何使用angularjs在复选框列表中推送选定的值


我有复选框列表,我想推选已选中/已选中的值。如果我将该值推入复选框列表,则应进行检查。例如,我推送三星Galaxy S6。如果我放三星Galaxy S6,我们需要查看商品数据因为三星Galaxy S6有一些报价。所以如果三星Galaxy S6被检查下拉列表应该填写提供消息。这是一个 演示我已经尝试过我的水平,但我无法解决请有人帮助我。

function Test1Controller($scope) {      
            var serverData = ["Samsung Galaxy Note", "Samsung Galaxy S6", "Samsung Galaxy Avant","Samsung Galaxy Young"];
            $scope.items= [] ;
    	//var selectedvalue = window.localStorage.getItem("selectedvalue");
    	// here selected value Samsung Galaxy S6
            var selectedvalue="Samsung Galaxy S6";
        for(var i=0;i<serverData.length;i++)
        {
            var modal = {
            name:serverData[i],
            selected:false
            };  
    	if (selectedvalue.indexOf(serverData[i]) >= 0 || null)
    	{
                modal.selected = true;

            }
         $scope.items.push(modal);        
        }
        //----------------------------Our Shop Offers----------------------------------------
        $scope.offers = [
        {
            id: "as23456",
            Store: "samsung",
            Offer_message:"1500rs off",
            modalname: "Samsung Galaxy Young"    

        },{
            id: "de34575",
            Store: "samsung",
            Offer_message:"20% Flat on Samsung Galaxy S6",
            modalname: "Samsung Galaxy S6"       

        },
        ]
        //-----------------------------------------------------------------------------------
   

$scope.selection = [];
     $scope.toggleSelection = function toggleSelection(item) {
     $scope.gotOffers=[];
     var idx = $scope.selection.indexOf(item);
      // is currently selected
     if (idx > -1) {
        $scope.selection.splice(idx, 1);
     }

      // is newly selected
      else {
        $scope.selection.push(item);
      }

      for(var i=0;i<$scope.selection.length;i++){
          for(var j=0;j<$scope.offers.length;j++){
            console.log($scope.selection[i].name  +"   "+ $scope.offers[j].modalname)
            if( $scope.selection[i].name  == $scope.offers[j].modalname){
              var idx = $scope.gotOffers.indexOf($scope.offers[j].Offer_message);
              if(idx == -1){
                console.log("inside idx")
                $scope.gotOffers.push($scope.offers[j]);
              }
            }
          }
        }
		console.log($scope.offers);		
    };
	//---------------------------------------------------------------------------------------
     $scope.check = function()	 
     {
         var checkedItems = [];
         console.log($scope.offerSelected)
        

     for(var i=0;i<$scope.items.length;i++)
        {
          if($scope.items[i].selected){
              checkedItems.push($scope.items[i].name);
          }
        }
              console.log(checkedItems) ; 
     }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>

<div ng-app>
  <div ng-controller="Test1Controller" >
    <div ng-repeat="item in items">
      <input type="checkbox" ng-model="item.selected"  ng-checked="selection.indexOf(item) > -1" ng-click="toggleSelection(item)"/> {{item.name}}
    </div>
    <select ng-show="gotOffers.length > 0" ng-model="offerSelected">
      <option ng-repeat="offer in gotOffers"  value="{{offer.id}}">{{offer.Offer_message}}</option>
    </select>
    <input type="button" name="submit" value="submit" ng-click="check()"/>
  </div>
</div>

7479
2017-12-11 16:26


起源

你能澄清一下你究竟遇到了什么问题吗?我可以在小提琴中看到,当你选择任何一个项目时(这里是三星galaxy s6),下拉列表会显示提供消息。 - Neel
也为什么这个代码 if (selectedvalue.indexOf(serverData[i]) >= 0 || null) { modal.selected = true; } 是必需的。没有这个也工作。我不明白是什么 selectedvalue 这里也宣布了2次。 - Neel
@komal:请解释一下。 - Monty


答案:


您可以通过解决几个问题使您的代码工作:

  1. 你正在使用两者 ng-model 和 ng-selected 在复选框输入上。按照 角度规范,这些不应该一起使用,因为它们会导致意外行为。

  2. 您正在使用 ng-click 更新可用的优惠。相反,您可以提供一个功能,根据选择的项目过滤要约列表。这意味着无论何时选择或取消选择项目,都会更新商品列表。

我已经缩减了你的演示,并在下面包含了一个固定版本:

function Test1Controller($scope) {
  $scope.items = [{"name": "Samsung Galaxy Note", "selected": false}, {"name": "Samsung Galaxy S6", "selected": true}, {"name": "Samsung Galaxy Avant", "selected": false}, {"name": "Samsung Galaxy Young","selected": false}];

  $scope.offers = [{
    id: "as23456",
    Store: "samsung",
    Offer_message: "1500rs off",
    modalname: "Samsung Galaxy Young"
  }, {
    id: "de34575",
    Store: "samsung",
    Offer_message: "20% Flat on Samsung Galaxy S6",
    modalname: "Samsung Galaxy S6"
  }, ];

  var selectedItems = function() {
    return $scope.items.filter(function(item) {
      return item.selected;
    });
  };

  $scope.availableOffers = function() {
    var items = selectedItems();
    return $scope.offers.filter(function(offer) {
      return items.some(function(item) {
        return item.name === offer.modalname;
      });
    });
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>

<div ng-app>
  <div ng-controller="Test1Controller" >
<div ng-repeat="item in items">
  <input type="checkbox" ng-model="item.selected" ng-click="toggleSelection(item)"/> {{item.name}}
</div>
<select ng-show="availableOffers().length > 0" ng-model="offerSelected">
  <option ng-repeat="offer in availableOffers()"  value="{{offer.id}}">{{offer.Offer_message}}</option>
</select>

  <input type="button" name="submit" value="submit" ng-click="check()"/>
  </div>
</div>


9
2017-12-22 05:23



没有什么工作。当我加载页面我想要显示一些复选框被选中。例如三星Galaxy S6被检查意味着下拉应该显示bcoz三星Galaxy S6有一些提供
很抱歉 - 我在发布答案时复制了错误的HTML代码段。代码现在应该正常工作。 - cmrn
谢谢我已经添加了完整的代码。谢谢您的回复


您可以通过在select上使用ng-options指令和使用a的过滤器来实现此目的 谓词 功能。

function(value,index):谓词函数可用于写入任意过滤器。为数组的每个元素调用该函数。最终结果是谓词返回true的那些元素的数组。

您可以查看一个工作示例 这里

HTML

<div ng-controller="OfferController">
    <div ng-repeat="item in items">
        <input type="checkbox" ng-model="item.selected" /> {{item.name}}
    </div>
    <select ng-show="hasResults" data-ng-options="offer.id as offer.Offer_message for offer in offers | filter : onGetFilter" ng-model="offerSelected"></select>
    <input type="button" name="submit" value="submit" ng-click="check()" />
    <br/>
    <label>Selected Offer {{offerSelected}}</label>
</div>

这个javascript

myApp.controller('OfferController', ['$scope', function ($scope) {
    var self = this;

    var serverData = ["Samsung Galaxy Note", "Samsung Galaxy S6", "Samsung Galaxy Avant", "Samsung Galaxy Young"];

    $scope.items = [];

    var selectedvalue = "Samsung Galaxy S6";

    for (var i = 0; i < serverData.length; i++) {
        var modal = {
            name: serverData[i],
            selected: false
        };
        if (selectedvalue.indexOf(serverData[i]) >= 0 || null) {
            modal.selected = true;
        }
        $scope.items.push(modal);
    }

    $scope.offers = [{
        id: "as23456",
        Store: "samsung",
        Offer_message: "1500rs off",
        modalname: "Samsung Galaxy Young"
    }, {
        id: "de34575",
        Store: "samsung",
        Offer_message: "20% Flat on Samsung Galaxy S6",
        modalname: "Samsung Galaxy S6"
    }];

    $scope.hasResults = false;

    $scope.onGetFilter = function (value, index) {
        if (index == 0 && $scope.hasResults) {
            $scope.hasResults = false;
        }
        for (var i = 0; i < $scope.items.length; i++) {
            if ($scope.items[i].selected) {
                if ($scope.items[i].name.indexOf(value.modalname) !== -1) {
                    $scope.hasResults = true;
                    return true;
                }
            }
        }
        return false;
    };

    function getSelectedItems() {
        var selectedItems = [];
        for (var i = 0; i < $scope.items.length; i++) {
            if ($scope.items[i].selected) {
                selectedItems.push($scope.items[i]);
            }
        }
        return selectedItems;
    }
}]);

3
2017-12-22 07:37



如何获取选中的复选框值和所选的商品ID
请看更新的答案 getSelectedItems 返回已检查项目的函数。您可以通过访问来检索所选的商品ID $scope.offerSelected 控制器中的属性 - Tjaart van der Walt


function Test1Controller($scope) {

  var serverData = 
  [
    "Samsung Galaxy Note",
    "Samsung Galaxy S6",
    "Samsung Galaxy Avant",
    "Samsung Galaxy Young"
  ];
  $scope.items = [];
  //var selectedvalue = window.localStorage.getItem("selectedvalue");
  // here selected value Samsung Galaxy S6
  var selectedvalue = "Samsung Galaxy S6";
  for (var i = 0; i < serverData.length; i++) {
    var modal = {
      name: serverData[i],
      selected: selectedvalue.indexOf(serverData[i]) >= 0
    };
    $scope.items.push(modal);

  }
  //----------------------------Our Shop Offers----------------------------------------
  $scope.offers = [{
      id: "as23456",
      Store: "samsung",
      Offer_message: "1500rs off",
      modalname: "Samsung Galaxy Young"

    }, {
      id: "de34575",
      Store: "samsung",
      Offer_message: "20% Flat on Samsung Galaxy S6",
      modalname: "Samsung Galaxy S6"

    }, ]
    //-----------------------------------------------------------------------------------
  $scope.selection = [];

  $scope.toggleSelection = function toggleSelection(item) {
    $scope.gotOffers = [];
    var idx = $scope.selection.indexOf(item);

    // is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // is newly selected
    else {
      $scope.selection.push(item);
    }

    for (var i = 0; i < $scope.selection.length; i++) {
      for (var j = 0; j < $scope.offers.length; j++) {
        console.log($scope.selection[i].name + "   " + $scope.offers[j].modalname)
        if ($scope.selection[i].name == $scope.offers[j].modalname) {
          var idx = $scope.gotOffers.indexOf($scope.offers[j].Offer_message);
          if (idx == -1) {
            console.log("inside idx")
            $scope.gotOffers.push($scope.offers[j]);
          }
        }
      }

    }
    console.log($scope.offers);

  };
  //---------------------------------------------------------------------------------------
  $scope.check = function()

  {


    var checkedItems = [];
    console.log($scope.offerSelected)
    for (var i = 0; i < $scope.items.length; i++) {
      if ($scope.items[i].selected) {
        checkedItems.push($scope.items[i].name);
      }
    }
    console.log(checkedItems);
  }



}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>

<div ng-app>
  <div ng-controller="Test1Controller">
    <div ng-repeat="item in items">
      <input type="checkbox" ng-model="item.selected" ng-checked="selection.indexOf(item) > -1" ng-click="toggleSelection(item)" /> {{item.name}}
    </div>
    <select ng-show="gotOffers.length > 0" ng-model="offerSelected">
      <option value="">Select offer</option>
      <option ng-repeat="offer in gotOffers" ng-value="offer.id">{{offer.Offer_message}}</option>
    </select>

    <input type="button" name="submit" value="submit" ng-click="check()" />
  </div>
</div>

根据我的理解你的问题是,我已经完成了代码。

如果你要求其他东西,请回复我


0
2017-12-28 10:01