How to dynamically display content based on option selection in AngularJS using ng-show

I am trying to create a functionality where my input field is bound to my select option. When the select option is set to Yes, I want the input field to be visible, and when it's set to No, I want the input field to be hidden.

(function(){

  var app = angular.module('spa',[

    $rootScope.options = [
      {
        id: 0,
        name: 'No'
      }, 
      {
        id: 1,
        name: 'Yes'
      }
    ]

  ]);  

}());


 <form name="newData" class="ng-scope ng-pristine ng-invalid ng-invalid-required" error-popup="newData" novalidate> 
    <div class="form-group item item-input item-select">
      <div class="input-label">
        Booking Fee Paid
      </div>
      <select name="booking" ng-model="user.booking" class="form-control ng-pristine ng-invalid ng-invalid-required" ng-options="option.name for option in options track by option.id" ng-init ="user.booking = options[0]" required>
      </select>
    </div>  

    <div class="row" ng-show="user.booking.name == 'Yes'">
        <div class="col">
        <div class="form-group item item-input">
                <input type="text" name="amount" ng-model="user.amount" class="form-control" placeholder="Amount">
            </div> 
        </div>
    </div>
  </form>

http://plnkr.co/edit/v0NrbTeigo3lm1njRu9A?p=preview

Any assistance would be greatly appreciated

Answer №1

If you're looking to learn more about AngularJS, I recommend checking out the beginner tutorials at angularjs.org.

For a practical example of what you're asking for, here is a sample code snippet:

angular.module('app', [])
    .controller('Sample', Sample);

function Sample() {
    this.options = [{
        id: 0,
        name: 'No'
    }, {
        id: 1,
        name: 'Yes'
    }];
    this.booking = this.options[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Sample as vm">
    
    <select name="booking" ng-model="vm.booking" ng-options="option.name for option in vm.options"></select>
    
    <pre>{{ vm.booking | json }}</pre>
    
    <input type="text" ng-show="vm.booking.name === 'Yes'"/>
</div>

Answer №2

The second parameter in the code specifies the required modules, not the implementation:

angular.module(name, [requires], [configFn]);

It seems like you encountered an injection error. Here is the corrected code:

http://example.com/sample-code

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

app.controller('MainController', function($scope) {
  $scope.items = [{
    id: 1,
    name: 'Apple'
  }, {
    id: 2,
    name: 'Banana'
  }];
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate this data into the HTML document?

I am an aspiring programmer who has self-taught programming and is now experimenting with Firebase Firestore. When attempting the following code: var docRef = db.collection("Marcus").doc("one") docRef.get().then(function(doc) { if (doc.exis ...

How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content. I have tried the following code: $('textarea').on(&apos ...

I'd like to know what sets next/router apart from next/navigation

Within Next.js, I've noticed that both next/router and next/navigation offer a useRouter() hook, each returning distinct objects. What is the reasoning behind having the same hook available in two separate routing packages within Next.js? ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

Changing a factory variable in AngularJS from a controller

I am currently working on a web application using Ionic 1 and AngularJS 1. Within my factory (UserFact) : .factory('UserFact', function() { var user = []; return { 'setUser': function(user) { ...

What is the process for accessing a local .json file from a remote machine or folder?

I am currently working on a project that involves a .json file stored in my local folder. Along with the file, I have Javascript code in the same directory to access and read the values from the .json file. To open the file, this is the line of code I use: ...

Using PHP to trigger alerts with MySQL data via AJAX from a separate file

I need to notify the first page from the second one, like in the example below: <?php $sql = "SELECT table_id, on, off FROM tables"; // retrieving and populating my table with information $stmt = mysqli_prepare($dbc, $sql); mysqli_stmt_exec ...

What steps does VSCode take to ensure that all necessary node dependencies are installed for its extensions?

As I work on constructing my own pluggable application, I've been curious about how vscode handles its extensions' dependencies. Does it run npm install in each extension directory and utilize those installations individually? Or does it have a c ...

Modifying table background color using AJAX and jQuery?

Scenario: My web page is designed to automatically search for a specific cell input by the user. If the cell has been input with a value, the table's background color will turn red; otherwise, it will remain green. Currently, the table has not been p ...

What is the process for transferring information from HTML to Python and then receiving the output in HTML?

I am completely unfamiliar with the connection between HTML and Python, so I am reaching out for some assistance. I hope that someone here can lend me a hand. Currently, my HTML is hosted on an Apache server, and I access the website using the address "". ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

What sets apart !$scope.variableName from $scope.variableName in AngularJS?

Greetings to all my fellow coders! As a newcomer in the field, I often find myself pondering over things like this. Would someone be kind enough to elucidate the dissimilarity between these two elements in AngularJs? $scope.variableName and !$scope.var ...

Float two DIVs horizontally with the same height using jQuery

Having a strange issue with the website I'm currently working on and can't seem to figure out what's causing it. Something is definitely off with my javascript, but I just can't pinpoint the exact problem. Here's the situation: I ...

Tips for customizing the AjaxComplete function for individual ajax calls

I need help figuring out how to display various loading symbols depending on the ajax call on my website. Currently, I only have a default loading symbol that appears in a fixed window at the center of the screen. The issue arises because I have multiple ...

Utilizing cross-domain AJAX for JSON requests

I'm currently on the website site.com attempting to retrieve some JSON data from my node.js server running on port 8080. Encountered this particular error message: XMLHttpRequest cannot load http://site.com:8080/json/1. Origin http://site.com is not ...

What could be the issue with trying to bind an event handler in this manner?

I'm having some trouble binding an event handler with jQuery: $(document).ready(function () { var newsScrollerForPage = new NewsScroller(); newsScrollerForPage.init(); $('#scroller-left-a').bind('on ...

Having trouble implementing the jQuery UI layout plugin in my Angular.js app with routing, specifically on the second view

Currently, I am developing a simple angular.js application that involves two views: a HOME view and an ALT view. My goal is to incorporate a jQuery UI Layout plug-in on the ALT view in order to create a layout with North, South, East, and West regions. Ho ...

Create a JavaScript program that can identify which number in a given array is different from the other two when two of the numbers in the array are equal

function checkThirdNumber() { let num1 = parseInt(document.querySelectorAll('.checkThirdInput')[0].value); let num2 = parseInt(document.querySelectorAll('.checkThirdInput')[1].value); let num3 = parseInt(document.querySelect ...

Learn how to easily toggle table column text visibility with a simple click

I have a working Angular 9 application where I've implemented a custom table to showcase the data. Upon clicking on a column, it triggers a custom modal dialog. The unique feature of my setup is that multiple dialog modals can be opened simultaneously ...

Modal's ng-click not triggering component's function

I am currently working on resolving an issue. My choice to use AngularJS is intentional, as I prefer not to load the entire NPM of Angular. Additionally, we heavily rely on Razor Syntax for the Web Layer. Implementation in Create.cshtml file <button ...