Set selection options depending on a different select element value in AngularJS

I almost tried my best to call this question, as I am with a real problem! I have two choices:

Choose 1:

<select ng-change="bankSelected()" ng-model="user.bankName">
    <option selected value="">Select</option>
    <option ng-repeat="bank in banks" value="{{bank.name}}">{{bank.name}}</option>
</select>

Choose 2:

<select ng-model="user.branch">
    <option selected value="">Select</option>
    <option ng-repeat="// what to do??"></option>
</select>

Function "bankSelected ()" in my controller:

$scope.bankSelected = function () {
    console.log('Bank selected: ' + $scope.user.bankName);
}

I have a JSON file into which I import all the bank objects, here is an example:

{
    "banks" : [
        {
            "name" : "Bank A",
            "branches" : [
                {
                    "name" : "Branch 1",
                    "code" : "1"
                },
                {
                    "name" : "Branch 2",
                    "code" : "2"
                }
            ]
        },
        {
            "name" : "Bank B",
            "branches" : [
                {
                    "name" : "Branch 3",
                    "code" : "3"
                },
                {
                    "name" : "Branch 4",
                    "code" : "4"
                },
                {
                    "name" : "Branch 5",
                    "code" : "5"
                }
            ]
        }
    ]
}

JSON, , 1000 . , 'Bank A' , , 'Branch 1' 'Branch 2'. , 'Bank B', 'Branch 3', 'Branch 4' 'Branch 5'. (, ), () . , , ?

AngularJS?

+4
1

bank ng-repeat

<select ng-model="user.bankName">
    <option selected value="">Select</option>
    <option ng-repeat="bank in banks" value="{{bank.name}}">{{bank.name}}</option>
</select>

branch ng-repeat

<select ng-model="user.branch" ng-show="user.bankName">
    <option selected value="">Select</option>
    <option ng-repeat="branch in getBranches(user.bankName)" value="{{branch.code}}">{{ branch.name }}</option>
</select>

getBranches() , , .

$scope.getBranches = function(selectedBank) {

    // get the selected bank object from the banks array
    var filteredBank = $filter('filter')($scope.banks, selectedBank);

    // return the branches of the selected bank
    return filteredBank[0].branches;
};

$filter,

app.controller('CtrlName', function($scope, $filter) {...

DEMO


- , :)

.

<select ng-model="user.bankName" ng-options="bank.name for bank in banks">
</select>

, user.bankName.branches.

<select ng-model="user.branch" ng-if="user.bankName" ng-options="branch.code as branch.name for branch in user.bankName.branches">
</select>

getBranches().

DEMO

+9

Source: https://habr.com/ru/post/1609296/


All Articles