简体   繁体   中英

Hide and Show elements based on values in Array in AngularJS

I have the following HTML code:

<div ng-controller="DemoController">
            <label class="list-group-item" ng-repeat="option in DesignOptions">
                <input type="radio" name="optionsRadios" value="{{option[0]}}" />
                {{option[1]}}</label>


            <label class="list-group-item" ng-repeat="option in StyleOptions">
                <input type="checkbox" value="{{option[1]}}">
                {{option[2]}}
            </label>
        </div

And I have the following AngularJS code:

<script type="text/javascript">
        var app = angular.module('myApp', []);

        app.controller('DemoController', function ($scope) {

            var json = '{"Table":[[4,"Full"],[5,"Half"]],"Table1":[[4,1,"Elbow Patch"],[5,2,"Roll Up"]]}';
            var obj = $.parseJSON(json);

            $scope.DesignOptions = obj.Table;
            $scope.StyleOptions = obj.Table1;

        });
    </script>

This gives me the following result:

在此处输入图片说明

Now, I need to display Elbow Patch checkbox only when Full radio button is selected. And Roll Up when Half radio button is selected. This is because, if you see obj.Table array, it has id of '4' for Full and obj.Table1 has id of '4' for Elbow Patch and so on.

I tried Angularjs - showing element based on a presence of id in array but could not modify it to work in my case as my array is very different.

Add a new property to your controller which will store the selected design option:

$scope.designOption = 4;    // default to Full

Add the binding to this property in the view:

<input ng-model="$parent.designOption" type="radio" value="{{option[0]}}" />

Add an ng-show directive to the checkbox label:

<label ng-repeat="option in StyleOptions" ng-show='option[0] == designOption'>

I've removed the class and name attributes from the element just to make the code clearer.

NB Need to reference the $parent scope on the radio input as the ng-repeat directive will create a scope for each repeated element and javascript prototypical inheritance rules means that using just 'designOption' will create a designOption property on the child scope and not use the one in your controller.

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