sharic19
sharic19

Reputation: 1139

AngularJS - Hide a form when a select option value equals specific value

Please help implement such functionality. If option value == 1, hide the form below.

<select ng-model="selection">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
   <option value="5">5</option>
<select>

<form ng-hide="isHidden"> <!-- Form to be hidden when option value == 1 -->
   <!-- Some html code here... -->
</form>

Here's a part of the controller.

$scope.isHidden = true;

if($scope.selection == '1'){
    $scope.isHidden = false;
}

The current code is not working. Please help me to implement this. Thanks.

Upvotes: 0

Views: 1375

Answers (3)

Jani Hyyti&#228;inen
Jani Hyyti&#228;inen

Reputation: 5407

You should handle the change event and put all of your logic to your JavaScript files. This not only separates your concerns but also makes it easier to debug. You could use $scope.$watch and handle the whole thing unobtrusively in controller, but since your logic is going to manipulate ui, it's better to have some hint in the ui ng-change for some other programmers of the logic. This would prevent situations like "where did the form go?" followed by an hour of searching the logic.

HTML:

<form name="myForm">
    <select ng-model="selection" ng-change="handleSelectionChange()">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    <select>
</form>

Controller:

$scope.handleSelectionChange = function(){
    if($scope.selection=='1'){
        document.myForm.style.display = 'none';
    }
};`

I cannot verify the functionality of the code on my mobile, so until I can, let this work as an idea of an approach. I will test the code as soon as I get to my desktop.

Upvotes: 0

James Allardice
James Allardice

Reputation: 166031

You could just refer to the selection in the ng-hide directive:

<form ng-hide="selection == '1'">
   <!-- Some html code here... -->
</form>

Here's a working example.

Upvotes: 3

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38488

You can add a watch to selection property:

$scope.$watch('selection',function(newValue){
    $scope.isHidden = newValue != '1';
});

Upvotes: 1

Related Questions