Controllers within controllers that fail to choose an option in a select tag dropdown will result in the hiding of another input element

My application utilizes nested controllers following John Papa's style guide, with a controller as approach. One of the controllers manages the form for client validation and submission, while the other is responsible for handling location-related functionality in the HTML view. Specifically, it should hide the STATE input field for countries that do not have states, preventing any input from occurring.

The country selection is made using a select tag populated by a JSON translation object from a factory, and selecting English works fine. However, when certain countries are selected, the STATE input field fails to hide or disappear as intended. I suspect this issue arises because the user's click on a country in the dropdown occurs outside the $digest cycle, so I tried using $timeout() to address this but with no success. Avoiding ng-click due to double clicks being triggered (one to open the select menu and another to make the selection) poses another challenge. Moreover, the countrySelected variable remains undefined in the SelectCountryController, puzzling me further. Even though hard coding a country yields the desired outcome upon page load, user selections from the dropdown never trigger the expected behavior.

Code snippet from the HTML:

<div name="postApartment4Rent" data-ng-controller="InputFormController as cntrl">
  <form id="residenceInput" name="residenceInput" data-ng-submit="cntrl.submit()">
        <div id="countryAndState" data-ng-controller="SelectCountryController as vm">
        <div class="boldHeading">
            <p>TEST Language: {{ vm.langKey }} </p> 
            <p translate>COUNTRY</p>
            <select data-ng-model="vm.countrySelected"
                data-ng-init="vm.countrySelected = vm.countrySelected || vm.countries[0].code"
                data-ng-options="country.code as country.text group by country.continent for country in vm.countries">
            </select>
        <p>TEST selected item is : {{vm.countrySelected}}</p>
        </div>

        <div id="stateProvince">
            <div id="stateDiv" data-ng-hide="vm.hideState">
                <p class="boldHeading" translate>STATE</p>
                <input type="text" id="state" name="state" data-ng-model="cntrl.input.state" size="50" maxlength="50" />
            </div>
        </div>
        </div>
  </form>
</div>

Here's an excerpt of the Angular/Javascript code inside the SelectCountryController:

(function() { 'use strict';
  angular.module('residenceApp').controller('SelectCountryController', SelectCountryController); //end of controller module
  SelectCountryController.$inject = ['$translate', 'selectCountryTranslateFactory', '$timeout'];

function SelectCountryController($translate, selectCountryTranslateFactory, $timeout) {
  var vm = this;        
  vm.langKey = {};
  vm.hideState = false;
  vm.countries = countries();
  vm.hideState = hideStateSelector();

function countries() {
  vm.langKey = $translate.use(); // Using use() as a getter
  return selectCountryTranslateFactory.withLangChoice(vm.langKey);
}

function hideStateSelector() {
  var countriesWithNoStates = ["AI", "AG", "AW", "BS", "BB", "BM"];
  if(countriesWithNoStates.indexOf(vm.countrySelected) > -1) {
            $timeout(function() {
                vm.hideState = true;
                angular.element('stateDiv').trigger('click');
                return vm.hideState;
            }, 10); //end of $timeout
        }
  } // End of hideStateSelector function
} // End of controller function
})();

If relevant, all these components are contained within a partial view.

Answer №1

Together, Mr. Laird and I have devised a solution and here is the code implementation for utilizing 'this' and $scope to update the view.

(function(angular) { 
  'use strict';
  angular.module('residenceApp').controller('SelectCountryController', SelectCountryController);
  SelectCountryController.$inject = ['$rootScope', '$translate', '$timeout', 'selectCountryTranslateFactory'];

  function SelectCountryController($scope, $translate, $timeout, selectCountryTranslateFactory) {
    var vm = this;        
    vm.langKey = {};
    vm.hideState = false;
    vm.countries = countries();
    $scope.countrySelected = '';
    
    function countries() {
      vm.langKey = $translate.use(); 
      return selectCountryTranslateFactory.withLangChoice(vm.langKey);
    }
    
    function hideStateSelector(countrySelected) {
      var countriesWithNoStates = ["AI", "AG", "AW", "BS", "BB", "BM"];
      
      if(countriesWithNoStates.indexOf(countrySelected) !== -1) {
        $timeout(function() { 
          vm.hideState = true; 
        }, 0);
      } else {
        vm.hideState = false;
      }
    }
    
    $scope.$watch('vm.countrySelected', function (newValue, oldValue) {
      hideStateSelector(countrySelected);
    });
  }

})(window.angular);

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

Running into memory issues while constructing the heap

After attempting to build and deploy our React application, I encountered the following error: FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory While I initially thought this was solely a JavaScript issue, I am uncert ...

What is the method for locating an element within an array?

The content being returned is presenting a challenge. How can I retrieve data from inside 0? I attempted to access it using date[0] without success const { data } = getData(); The result of console.log(data) is shown below: enter image description here ...

Issue with JQuery Validation: Some checkbox values are not being successfully posted

Currently experiencing issues with validating checkboxes. Utilizing the jQuery plugin validation found here: The scenario is that there are three checkboxes and at least one of them must be checked. The original form code for these checkboxes is as follow ...

Utilize jQuery method in HTML to perform parsing operation

Is it possible to invoke my jQuery function from within my HTML code? Here is the code snippet: HTML section: <td style="text-align:left;" align="left" > <div id="bulletin-timestamp" > doTimeStamp(${bulletinTimeStamp[status.index ...

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

How to access a variable from within a Phonegap DB function and return it outside of the

I'm struggling with a phonegap db JavaScript script that isn't returning the final string variable "feeds" outside the function. It's currently showing as "undefined". I need help making the necessary changes to properly return the "feeds" v ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

Can variables be utilized with the toastController in Ionic or Angular framework?

Is it possible to present a toast message to the user with their first name that is stored in a variable? If so, how can I achieve this? I would like to create something similar to the following: this.toastCtrl.create({ message: "Welcome user.firstname ...

Struggling with implementing a materialize modal?

I am encountering a problem with Materialize. This time, I am trying to create a modal div, but it doesn't seem to be working. The button is created, but when I click on it, nothing happens. I have made sure to link all the necessary Materialize files ...

What is the method for indicating the data type in an XDR request?

Currently, I am successfully using XDR for cross domain resource sharing in IE. However, I am facing an issue with specifying the return dataType to receive JSON as responseText. Below is the snippet of my code: if (window.XDomainRequest && $.browser.m ...

Maintain the fancybox open even in case of ajax errors

I'm having an issue with my code where the fancybox closes automatically after displaying the error message briefly. I want it to remain open so that users have more time to fix their errors. What could be causing this problem? $(document).ready(func ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

Limit the number input to only allow values between 0 and 100

I am utilizing the Number input component from MUI, which includes Increment and Decrement buttons for adjusting numbers. Is there a method to limit the input to only accept values ranging from 0 to 100 ? Additionally, how can I decrease the width of the ...

Elevate the value within a function and refresh the said function

I'm currently facing a challenge with this particular piece of code, let spin = new TimelineMax(); spin.to($('.particle'), 150, { rotation: 360, repeat: -1, transformOrigin: '50% 50%', ease: Linear.easeNone }); Th ...

What is the best way to set the length of an undefined item in an object to 0 in reactjs?

I am facing a challenge keeping track of scores within each article and displaying them accurately. The issue arises when there is a missing "up" or "down" item in the object. Below is the data containing all the votes: const votes = { "1": { "up": ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

Activating text wrapping functionality

My current project involves converting HTML to PDF using jsPDF. In order to ensure that every word appears in the exact location as it does in the original HTML, I decided to wrap each word in <span> tags. Specifically, I have a font tag (not added b ...

What is the best technique for creating a preloader that can seamlessly fill the background of a vector image?

I am looking for guidance on creating a CSS3 preloader using a vector image. My goal is to have the logo start off transparent with only the border visible, and as the loading occurs, fill in from bottom to top with the background color. Thank you to ever ...

How to retrieve query parameters using Angular 2's HTTP GET method

Seeking assistance on my Ionic 2 app built with Angular 2 and TypeScript. I am familiar with older versions of Angular, but still adjusting to this new environment. I have set up my API with basic query strings (e.g domain.com?state=ca&city=somename) ...