简体   繁体   中英

Show a dropdown based on proper selected radio button

Question:

How do I show all radio buttons but only one dropdown. This shown dropdown is one that reflects the currently selected radiobtn?

Live Code

Html:

<form ng-app="app" ng-controller="Ctrl">
    <div class="color-pick" ng-repeat="(key, val) in productData.colors_and_sizes.data">
        <input type="radio" name="colors" ng-model="myColor" ng-value="{{key}}" />{{key}}
        <div class="size-pick">
            <select ng-model="mySize" ng-options="size for size in val.sizes.split(',')"></select>
        </div>
    </div>
</form>

javascript:

var app = angular.module("app", []);

app.controller('Ctrl', function ($scope, $filter, $http) {
 $scope.productData = {
  "colors_and_sizes": {
    "data": {
      "Black": {
        "sizes": "X Small, Small, Medium, Large, Xlarge, XX Large"
      },
      "Blue": {
        "sizes": "X Small, Small, Medium, Large, Xlarge, XX Large"
      }
    }
  }
};

});

Use the ng-hide or show directive on the div wrapping the select statement. The problem you're probably running into is that each ng-repeat iteration creates it's own scope, this means that each ng-model you create is completely independent.

You can see this here: http://jsfiddle.net/v2r9y6x2/ , when each select radio is clicked it prints a different value underneath itself, in both cases this is the value of ng-Model being set:

You can fix this by referring to the parent scope with $parent.property instead of just the property name. This will assign the value to the parent controllers scope and work as you expect.

http://jsfiddle.net/djwruftr/

<form ng-app="app" ng-controller="Ctrl">
    <div class="color-pick" ng-repeat="(key, val) in productData.colors_and_sizes.data">
        <input type="radio" name="colors" ng-model="$parent.myColor" ng-value="key" />{{key}}
        <div class="size-pick" ng-show="$parent.myColor==key">
            <select ng-model="$parent.mySize" ng-options="size for size in val.sizes.split(',')"></select>
        </div>
    </div>
    myColor: {{myColor}}<br/>
    mySize: {{mySize}}
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM