Angularjs trigger country state dependency

后端 未结 4 2020
[愿得一人]
[愿得一人] 2021-01-05 13:03

Can someone please help me make my example of Country/State drop down dependency work?

I intentionally created JSON in this way because I want the dependency to be g

4条回答
  •  攒了一身酷
    2021-01-05 13:41

    I suggest you a bit of refactoring to your data model - it seems tangled. Let's store counties and states in two arrays:

    $scope.countries = [{
        "name": "USA",
        "id": 1
      },{
        "name": "Canada",
        "id": 2
    }];
    $scope.states = [{
        "name": "Alabama",
        "id": 1,
        "countryId": 1
      }, {
        "name": "Alaska",
        "id": 2,
        "countryId": 1
      }, {
        "name": "Arizona",
        "id": 3,
        "countryId": 1
      }, {
        "name": "Alberta",
        "id": 4,
        "countryId": 2
      }, {
        "name": "British columbia",
        "id": 5,
        "countryId": 2
    }];
    

    Having this, we can write selects for data:

    
    
    

    It's a pity we cannot use if expressions in selectors - if we can, we do not need a single line of JS! But we need:

    $scope.updateCountry = function(){
      $scope.availableStates = [];
    
      angular.forEach($scope.states, function(value){
        if(value.countryId == $scope.country.id){
          $scope.availableStates.push(value);
        }
      });
    }
    

    And that's all. Here is a working plunk for you.

提交回复
热议问题