简体   繁体   中英

how to toggle input box based select option in angular js?

I am trying to add an input box to the DOM based on the user selection:

option1 other option 3 otherwise remove input box from dom, how can do it, i tried bellow code but it is not working?

html--

<select ng-model="myDropDown">
      <option value="one">One</option>
      <option value="two">Two</option>
      <option value="three">Three</option>
</select>    <p ng-if="myDropDown=='two' || ans=='three'">
   <input type="text" ng-model="fname" name="fname" />
</p>

jsFiddle--> http://jsfiddle.net/EZbfM/717/

The reason ng-if is behaving unexpectedly is because you seem to have referenced an ancient version of AngularJS (1.0.2). If you update it to a more recent version, ng-if will work as expected.

See the link here for the issue related to the evaluation issue of ng-if : https://github.com/angular/angular.js/pull/4005

Do you want to show it when the dropdown is on one or on three, otherwise not?

change

<input ng-if="myDropDown=='two'" type="text">

to

 <input ng-hide="myDropDown=='two'" type="text">

It will always render then, but only show if the option chosen is one or three

If I understand well, you are trying to display an element based on myDropDown value. You can write complex expressions as && or || in ng-show with the following synthax:

<div ng-show="myDropDown == 'two' || myDropDown == 'three'">
    <!-- Will be displayed only when you select 'two' or 'three' -->
    <input type="text" ng-model="fname"/>
</div>

Fiddle with ng-show

Fiddle with ng-if

DEMO

 var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', ['$scope',function($scope) { }]); 
 <div ng-app="myApp" ng-controller="MyCtrl"> <select ng-model="myDropDown"> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> <p ng-if="myDropDown=='two' || myDropDown=='three'"> <input type="text" ng-model="fname" name="fname" /> </p> </div> 

Here is working fine..

 var app = angular.module('exApp', []); app.controller('ctrl', function($scope){ $scope.myDropDown = "one"; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script> <body ng-app="exApp" ng-controller="ctrl"> <div> <select data-ng-model="myDropDown"> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> <p> <input ng-model="comment" ng-if="myDropDown != 'two'" type="text"> </p> </div> </body> 

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