web-dev-qa-db-fra.com

Angularjs Filter data with dropdown

Je suis un peu nouveau dans angularjs et javascript, alors soyez gentil, j'ai deux éléments de liste déroulante (Ionic Select) qui contiennent tous deux des données d'un service. Le problème est que je dois les filtrer afin de travailler ensemble comme: si je choisis une entreprise dans la première liste déroulante, seuls les représentants à l'intérieur de cette entreprise devraient s'afficher dans l'autre liste déroulante.

J'ai essayé d'utiliser | filter: byID comme je l'ai suivi dans la documentation d'Angularjs mais je ne pense pas que ce soit la bonne façon de le faire, je ne sais pas.

HTML:

<label class="item item-input item-select"">
    <div class="input-label">
      Company:
    </div>
    <select>
      <option ng-repeat="x in company">{{x.compname}}</option>
      <option selected>Select</option>      
    </select>
  </label>
   <div class="list">
  <label class="item item-input item-select">
    <div class="input-label">
      Rep:
    </div>
    <select>
       <option ng-repeat="x in represent">{{x.repname}}</option>
      <option selected>Select</option>
    </select>
  </label>

Javascript:

/*=========================Get All Companies=========================*/
 $http.get("http://localhost:15021/Service1.svc/GetAllComp")
      .success(function(data) {

        var obj = data;
        var SComp = [];


    angular.forEach(obj, function(index, element) {

    angular.forEach(index, function(indexN, elementN) {        

        SComp.Push({compid: indexN.CompID, compname: indexN.CompName});

        $scope.company = SComp;
    });    

    });          
            })
/*=========================Get All Companies=========================*/

/*=========================Get All Reps=========================*/
 $http.get("http://localhost:15021/Service1.svc/GetAllReps")
      .success(function(data) {

        var obj = data;
        var SReps = [];


    angular.forEach(obj, function(index, element) {

    angular.forEach(index, function(indexN, elementN) {        

        SReps.Push({repid: indexN.RepID, repname: indexN.RepName, fkc :indexN.fk_CompID});

        $scope.represent = SReps;
    });    

    });          
            })
/*=========================Get All Reps=========================*/
7
user2413453

Vous pouvez résoudre ce problème comme mon processus de solution: ma solution comme votre problème. au premier affichage District liste et affichage Thana liste selon District sélectionné. en utilisant l'expression filter

En HTML:

<div>
        <form class="form-horizontal">
            <div class="form-group">
                <div class="col-md-3"><label><i class="fa fa-question-circle fa-fw"></i> District List</label></div>
                <div class="col-md-4">
                    <select class="form-control" ng-model="selectedDist" ng-options="district.name for district in districts">
                        <option value="">Select</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-3"><label><i class="fa fa-question-circle fa-fw"></i> Thana List</label></div>
                <div class="col-md-4">
                    <select class="form-control" ng-model="selectedThana" ng-options="thana.name for thana in thanas | filter: filterExpression">
                        <option value="">Select</option>
                    </select>
                </div>
            </div>
        </form>
    </div>

Dans le contrôleur:

            $scope.selectedDist={};
            $scope.districts = [
                {id: 1, name: 'Dhaka'},
                {id: 2, name: 'Goplaganj'},
                {id: 3, name: 'Faridpur'}
            ];

            $scope.thanas = [
                {id: 1, name: 'Mirpur', dId: 1},
                {id: 2, name: 'Uttra', dId: 1},
                {id: 3, name: 'Shahabag', dId: 1},
                {id: 4, name: 'Kotalipara', dId: 2},
                {id: 5, name: 'Kashiani', dId: 2},
                {id: 6, name: 'Moksedpur', dId: 2},
                {id: 7, name: 'Vanga', dId: 3},
                {id: 8, name: 'faridpur', dId: 3}
            ];
            $scope.filterExpression = function(thana) {
                return (thana.dId === $scope.selectedDist.id );
            };

NB: Ici filterExpression est une fonction personnalisée qui renvoie des valeurs lorsque l'ID de district sélectionné est égal à dId dans thana.

11
Shaishab Roy
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope,$window, $http) {
   $scope.myFunc = function(x) {
                $scope.name = x.Name;
                $scope.country = x.Country;
                $scope.city = x.City;
                $scope.x = x;
                $("#myModal").modal();
   };
   
   $scope.saveData = function(x) {
                if(x == ''){
                        x = angular.copy($scope.names[0]);
                        x.Name = $scope.name;
                        x.Country = $scope.country;
                        x.City = $scope.city;
                        $scope.names.Push(x);
                }
                else{
                        x.Name = $scope.name;
                        x.Country = $scope.country;     
                        x.City = $scope.city;   
                }
        };
  
  $scope.newData = function() {
                $scope.name = "";
                $scope.country = "";
                $scope.city = "";
                $scope.x = "";
                $("#myModal").modal();
   };

        $scope.myDelete = function(x) {
                if(x.Name=='' && x.Country=='' && x.City==''){
                        var index = $scope.names.indexOf(x);
                        $scope.names.splice(index, 1);
                }
                else{
                        var deletedata = $window.confirm('are you absolutely sure you want to delete?');
                        if (deletedata) {
                        alert('i am');
                                var index = $scope.names.indexOf(x);
                                $scope.names.splice(index, 1);    
                        }
                }
        };
        $scope.filterExpression = function(x) {
                                //alert($scope.country.id);
                return (x.countryId === $scope.country.countryId );
            };
                        
   $scope.names =  [{"Name":"Alfreds Futterkiste","City":"","Country":""},{"Name":"Ana Trujillo Emparedados y helados","City":"","Country":""}]
   $scope.countryList = [
        {countryName : "Pakistan", countryId : 1},
        {countryName : "UK", countryId : 2},
        {countryName : "Sweden", countryId : 3}
    ];
        $scope.cityList = [
        {cityName : "Karachi", cityId : 1, countryId:1},
        {cityName : "London", cityId : 2, countryId:11},
        {cityName : "Sweden City", cityId : 3, countryId:3}
    ];
});
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<style>
.table tr {
    cursor: pointer;
}
</style>
<div class="container" ng-app="myApp" ng-controller="customersCtrl">
 <pre>{{names}}</pre>
  <h2>Hover Rows</h2>
  <p>The .table-hover class enables a hover state on table rows:</p>            
  <table class="table table-hover">
    <thead>
      <tr>
        <th>Sr.No</th>
        <th>Name</th>
        <th>Country</th>
                 <th>City</th>
                <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="x in names" ng-dblclick="myFunc(x)" >
        <td>{{ $index + 1 }}</td>
                <td>{{ x.Name }}</td>
                <td>{{ x.Country.countryName }}</td>
                <td>{{ x.City.cityName }}</td>
                <td><span class="glyphicon glyphicon-remove" ng-click="myDelete(x)"></span></td>
         </tr>
        </tbody>
        <tfoot>
                <tr ng-click="newData()">
                        <td  colspan="4">
                        </td>
                        <td>
                                <span class="glyphicon glyphicon-plus" ng-click="newData()" cursor="" ></span>
                        </td>
                </tr>
        </tfoot>
        
  </table>
  
    <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title" ng-if="x!=''">Edit Record</h4>
                  <h4 class="modal-title" ng-if="x==''">Save Record</h4>
        </div>
        <div class="modal-body">
        <div class="form-group">
                        <label for="name">Name:</label>
                        <input type="text" class="form-control" id="name" ng-model="name">
                </div>
                <div class="form-group">
                        <label for="country">Country:</label>
                        <!-- <input type="text" class="form-control" id="country" ng-model="country"> -->
                        <select class="form-control" ng-model="country" ng-options="x.countryName for x in countryList"></select>
                </div>
                <div class="form-group">
                        <label for="country">City:</label>
                        <select class="form-control" ng-model="city" ng-options="x.cityName for x in cityList | filter:filterExpression"></select>
                </div>
                <input type="hidden" ng-model="x" />
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="saveData(x)">Save</button>
                  <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="myDelete(x)" ng-if="x!=''">Delete</button>
        </div>
      </div>
      
    </div>
  </div>
</div>
</body>
</html>
0
raza