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

Guide to changing the background colors of multiple elements when hovered over by the mouse?

I want to customize my website's search bar by changing the background color when it is hovered over. Currently, the search bar has two main elements: the text box and the submit button. I have successfully programmed the text box element to change to ...

Getting the Mongoose Model using Express parameters is a simple process

Is it possible to dynamically fetch a mongoose model based on the req.params.model? Check out this example of a Schema const mongoose = require("mongoose"); const Schema = mongoose.Schema; const SmartSchema = new Schema({ SmartPriority: { type: Stri ...

Updating database with Ajax when the button is clicked

Seeking guidance with a project as I am still grasping the concepts of javascript and jquery. The goal is to update a database entry upon clicking a button, where the content of the button is fetched from the database. Initial step involves querying the d ...

Manipulating the DOM results in the SWF being reloaded

Currently, I am utilizing jQuery to insert an SWF into the DOM. However, when the SWF loads and I attempt to clone or wrap it, the SWF ends up reloading. Preventing this reload is crucial for me. Here's an example: $('#test9').before(&apo ...

Show JSON array items

My php file (history.php) generates a JSON object $i=1; $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10"); while($rs=mysql_fetch_array($q)){ $response[$i] = $rs[&ap ...

What is the process for programmatically aligning two cards side by side using Material UI in React after retrieving data from an API?

I am currently working with data from an API that I need to display in the format of cards, arranged side by side. To achieve this, I have been using an array and passing the data to components programmatically. You can see the output image and my code bel ...

The echo statement is failing to show any value following the ajax request

I am in need of assistance. I would like to output the value from a PHP echo statement using an AJAX call. Currently, the code is functioning without any errors. When I select options from a dropdown menu, the value is displayed on the console by using con ...

Switch between adding elements to various div containers

Can we implement a functionality where clicking an anchor tag moves the .item from .region1 to .region2, and then moving it back to .region1 when clicked again? Essentially creating a toggle behavior? <a href="#" class="btn">Click</div> &l ...

Would you like to learn how to dynamically alter a button's color upon clicking it and revert it back to its original color upon clicking it again?

My Upvote button starts off transparent, but when I click on it, the background color changes to green. What I need is for the button to become transparent again when clicked a second time. I've attempted using the following code snippet: function ...

Interaction issue with Material UI and React tabs: hovering fails to open and close tabs correctly

I am currently immersed in a project that involves React and Material UI. My goal is to create tabs that trigger a menu upon hovering, but I seem to be facing some challenges with this functionality. That's why I'm reaching out here for assistanc ...

What could be causing my line chart to omit some of my data points?

I'm having trouble with my line chart, as it's not covering all the points I intended. The maximum value on the y-axis seems to be 783, but I want it to cover all the points. Take a look at the image below to see what I mean: https://i.sstatic. ...

Switching icon with jQuery upon clicking

I'm just starting to learn jQuery and I'm working on changing the font icon class when clicked to display a drop down. Right now, it changes the icon and drops down the content as expected. However, I'm facing an issue where I want the icon ...

The functionality of Angular/Typescript class.name appears to fail during a production build

Using Angular 5, I encountered an unusual problem with the class.name property. We have a TypeScript function as shown below: export class ApiService { public list<T>(c: new(values: Object)=> T) { var cname = c.name; .... } } When ...

Tips for effectively utilizing Vuelidate to display errors selectively after the user has completed input:

I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it. <b-form @submit.prevent="onSubmit"> <input type="hidden" name="_token" :value="csrf" /> <transition-group name="fade"> <b-form ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

It appears that the ngRepeatWatch feature is causing a slowdown in Batarang

After reviewing the Batarang analysis of my AngularJS app, I have discovered the following: ngRepeatWatch | 64.2% | 136.0ms Surprisingly, this instruction takes up 10 times more time than the next reported instructions. Could this indicate that I am pot ...

Encountering issues with properly updating the Vuex store

Looking at my Vuex 2 store: const datastore = new Vuex.Store({ state: { socketcluster: { connection: false, channels: [] }, selected_offers: [] }, mutations: { addOffer: function(offer) { datastore.state.s ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

What is the reason behind Express exporting a function instead of an object in the initial stages?

In Node.js, when utilizing express, we start by using const express = require('express') to bring in the express module, which will then yield a function. Afterward, we proceed with const app = express() My inquiry is as follows: What exactly ...