Search code examples
angularjsangularjs-scopeangular-filters

Filter ng-options based on multiple controls or ng-models


Situation:

I have a back-end Laravel 5 and front-end AngularJS. Application is about allowing users to select multiple dependent very high-value products.

A. User selects a product from a drop-down - select-option. Product is added to a cart.

B. Then user clicks on Add button to add more products, this adds a row dynamically with drop-down select-option HTML element. This is done dynamically using AngularJS with $compile / $scope to add compiled HTML.

C. When user adds a row, initially product drop-down select-option has no value selected.

D. User selects a product from drop-down select-option. Product is added to a cart.

E. User may keep on adding around 50 products. Look at this UI:

UI Looks like

Now the condition is, when a new row is added the relevant drop-down should not show any product that is already selected in any of the drop-downs above.

Can someone please help me?

Thanks!


Solution

  • Try this. hope it will work.
    var app = angular.module('plunker', []);

    app.controller('MainCtrl', function($scope,$filter) {
      $scope.rep = [];
      $scope.xyz = function(){
        var sahed = $filter('filter')($scope.rep, $scope.sel) ;
        if(sahed.length <= 0){
           $scope.rep.push($scope.sel)
           return false;
        }
    
      };
      $scope.coll =[
       {id: 1,
       rate : 50,
       base_price : 50,
         product_name : 'ab'
       },
       {id: 2,
       rate : 50,
       base_price : 505,
        product_name : 'abc' 
       },
       {id: 3,
       rate : 520,
       base_price : 500,
         product_name : 'abcd'
       },
       {id: 4,
       rate : 50,
       base_price : 505,
        product_name : 'abcef' 
       },
      ];
    });
    

    and here the html

     <body ng-controller="MainCtrl">
        <select name="sel" id="sel" ng-model="sel"
        ng-options="x as x.product_name for x in coll track by x.id" ng-change="xyz()">
          <option value="">select product</option>
        </select>
        <table border="0">
          <thead>
            <tr>
              <td>name</td>
              <td>price</td>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="x in rep">
              <td>{{x.product_name}}</td>
              <td>{{x.base_price}}</td>
            </tr>
          </tbody>
        </table>
      </body>
    

    For example see it https://plnkr.co/edit/pXNkwisa7A3aFBPmIB0G?p=preview