Add the $scope ng-click event to a previously hidden element once it becomes visible

If you need a clearer explanation, feel free to ask. I have incorporated a global search function into the header of my website. I am looking to show a separate input box for mobile search that utilizes the same ng-click event, but the input field remains hidden when the page initially loads. The challenge I'm facing is capturing the input value from the hidden mobile input field upon activation of the ng-click event.

The main issues revolve around the search click function not identifying the correct ng-model once the function is executed. This could be due to the fact that since the hidden elements are not visible on page load, the ng-model="searchQueryStringMobile" isn't properly applied to the scope.

My query pertains to how I can ensure that ng-model="searchQueryStringMobile" is added to the scope after it becomes visible following a click event like ng-click="flipNav('search")", so that it doesn't return undefined when triggering ng-click="loadSearchResults".

Below is the code snippet:

HTML:

<div ng-controller="HeaderCtrl as header" class="container">
    <div id="jesusSearchTop">
        <input ng-model="searchQueryString" class="jesusSearchInput autoCompSearch" type="search" placeholder="Search..." autocomplete="off" />
        <select ng-model="searchDDL.item" class="jesusSearchSelect" ng-options="item.name for item in searchDDL track by item.id"></select>
        <div class="jesusSearchHolder">
            <img class="goSearch" ng-model="jesusSearch" ng-click="loadSearchResults('norm')" src="/EMR4/img/gui_icons/searchIcon.png" alt="Search EMR" />
        </div>
    </div>
    <div id="siteControls">
        <div id="siteSearch" class="siteControl" ng-click="flipNav('search')"></div>    
    </div>
    <div ng-switch="dd" class="dropDown">
        <div ng-switch-when="none" style="display:none"></div>
        <div ng-switch-when="search" class="dropMenu listStyle4" id="Search">
            <input ng-model="searchQueryStringMobile" class="jesusSearchInput" type="text" placeholder="Search..." autocomplete="off" />
            <select ng-model="searchDDL.item" class="jesusSearchSelect" ng-options="item.name for item in searchDDL track by item.id"></select>
            <div class="jesusSearchHolder">
                <img class="goSearch" ng-model="jesusSearchMobile" ng-click="loadSearchResults('mob')" src="/EMR4/img/gui_icons/searchIcon.png" alt="Search EMR" />
            </div>
        </div>
    </div>
    <div class="clr"></div>
</div>

Controller:

app.controller('HeaderCtrl', function ($scope, $http, $location, populateDDL) {
            $http.get(badge.credentials[7].home+'data.JSON')
            .success(function(data, status, headers, config) {
                $scope.header = data.header;
                $scope.searchOptions = new populateDDL('tblWebMenuItems',badge.credentials[1].key).
                then(function(response) {
                    $scope.searchDDL = response.tblWebMenuItems
                    $scope.searchDDL.item = $scope.searchDDL[0];
                });
            })
            .error(function(data, status, headers, config) {
                console.log(data+', '+status+', '+headers+', '+config);
            });
            $scope.flipNav = function(choice){
                if ($scope.dd === choice) {
                    console.log(choice);
                    $scope.dd = "none";
                }else {
                    $scope.dd = choice;
                }
            };
            $scope.loadSearchResults = function(uv) {
                var loader;
                if (uv === "mob") {
                    loader = $scope.searchQueryStringMobile;
                }else if (uv === "norm") {
                    loader = $scope.searchQueryString;
                }
                console.log(uv+' - '+loader);
                if (loader == null || loader < 2) {
                    alert('Please refine your search and continue, Thank you!');
                }else {
                    $location.path("/search/"+$scope.searchDDL.item.name.toLowerCase()+"/");
                    $location.search("type",$scope.searchDDL.item.name.toLowerCase());
                    $location.search("query", loader);
                }
            };
        });

Answer №1

After testing your code, it seems like the issue lies with the ng-switch directive. The problem arises because ng-switch creates a new scope that is a child of its parent's scope. To resolve this, you can use

ng-model=$parent.searchQueryStringMobile
or switch to using ng-show instead of ng-swtich. Unlike ng-switch, ng-show does not create a new child scope but simply manipulates the CSS property display to hide or show elements. By using $parent, you can access items from the parent scope within the child scope. In your case, $scope.searchQueryStringMobile is in the parent scope of the ng-switch's scope. Here is the updated working plunk: click here

To fix this issue, modify your ng-switch markup as follows:

<div ng-switch="dd" class="dropDown">
    <div ng-switch-when="none" style="display:none"></div>
    <div  ng-switch-when="search" class="dropMenu listStyle4" id="Search">
        <input ng-model="$parent.searchQueryStringMobile" class="jesusSearchInput" type="text" placeholder="Search..." autocomplete="off" />
        <select ng-model="searchDDL.item" class="jesusSearchSelect" ng-options="item.name for item in searchDDL track by item.id"></select>
        <div class="jesusSearchHolder">
            <img class="goSearch" ng-model="jesusSearchMobile" ng-click="loadSearchResults('mob')" src="/EMR4/img/gui_icons/searchIcon.png" alt="Search EMR" />
        </div>
    </div>
</div>

Take note of the ng-model attribute for the input element in the modified code.

Answer №2

It seems that your issue is quite simple. The ng-switch directive, like ng-if, creates a new scope. This means that when you use ng-model, you are assigning the property to this new scope rather than the scope used by your controller.

A solution would be to either use the controller as syntax or create a property of an object on the scope. To demonstrate this, I have provided an example for you.

As shown, {{a}} does not work outside the new scope, but {{x.b}} works perfectly fine.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-init="x = {}; show = 'first'">
  <button type="button" ng-click="show = 'first'">show first</button><br>
  <button type="button" ng-click="show = 'second'">show second</button><br>
  a = {{a}}<br>
  x.b = {{x.b}}
  <div ng-switch="show">
    <div ng-switch-when="first">
      <input type="text" ng-model="a">
    </div>
    <div ng-switch-when="second">
      <input type="text" ng-model="x.b">
    </div>
  </div>
</div>

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

Having issues with my jQuery getJSON request. It's returning an empty response even though

I have been struggling to find a solution to this particular issue with no luck... Here is the jQuery getJSON request that I am working on: $.getJSON("http://localhost:8080/context/json/removeEntity.html", { contentId : 1, entIndex : entityIndex ...

Upgrade your AngularJS codebase with Angular 2+ services

Attempting to adapt an Angular 2+ service for use in an AngularJS project. app/users.service.ts import { Injectable } from '@angular/core'; @Injectable() export class UsersService { private users: any = [ { id: 1, name: 'john&a ...

cheerio scraping results in an array that is devoid of any data

Struggling to extract data from a website with the URL https://buff.163.com/market/csgo#tab=buying&page_num=1 using request-promise and cheerio. Check out my code snippet below: const request = require('request-promise'); const cheerio = requ ...

Distinguishing between a regular JavaScript variable and one annotated with a dollar sign

Many responses have addressed the question of using a dollar sign in JavaScript variables. In essence, the dollar sign functions as an identifier in JavaScript variables. However, I am curious if there are other distinctions between regular variables and ...

Modifying data within nested objects using Typescript

Imagine having an object like this: { b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" }, ​ pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" } } with the in ...

Error code E401 is being encountered with npm, indicating either an incorrect password has been provided or the

My Node version is 10.15.0 and my NPM version is currently at 6.8.4. After updating npm to 14.16.0 and node to 7.6.2, I encountered the following error - npm ERR! code E401 npm ERR! Incorrect or missing password. npm ERR! If you were trying to log in, ...

Encountered an issue when attempting to select the password field in order to log into a Google account using

Having some trouble automating the login process for my Gmail account. Managed to find the email element with an ID, but hitting a roadblock trying to locate the Password element as it doesn't have an ID. Here's what I've attempted: passw ...

Make sure that the click event listener is set up on the anchor element so that it also affects its children

Currently, I have implemented a click event listener on my anchor elements. However, the anchors contain a span element within them, and the event listener does not function properly if you click on the span inside the anchor. document.addEventListene ...

Are instance prototypes exhibiting static behavior?

I'm in the process of creating a game for Windows 8 using HTML/Javascript and WinJS, but I'm running into issues with "prototypes" acting statically when they shouldn't. This is my first time working extensively with Javascript and dealing w ...

The AJAX validation process fails to run prior to the execution of the login PHP script

My attempt to implement AJAX for form validation is not successful and I'm unsure why. Despite my efforts, the form still redirects to login_action.php instead of performing the AJAX validation as intended. I have designed a modal login form and wish ...

Is it possible to transfer the reactivity of a Vue ref to another ref while reassigning it?

Below is a simplified version of my Vue component: <template> <div @click="loadEvents">{{ loading }}</div> </template> <script setup> import { ref } from 'vue' let loading = ref(false) loadEvents() func ...

Click the button to add content to the top section of the div using jQuery

Looking for some assistance with a web development issue I'm facing. Here's the scenario: I have two sections on my webpage - TOP and BOTTOM. In the bottom section, there are 3 list records each with a checkbox and button. What I need help with ...

Issue with an external library in Angular 2

After generating my Angular 2 library using the yeoman generator and adding it to my main Angular project, I encountered errors when running the app in production mode. The specific errors include: WARNING in ./src/$$_gendir/app/services/main/main.compone ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

What is the meaning of this CSS acronym?

div[id^=picture]:target{ /*applying various styles here*/ } I stumbled upon the snippet of code shown above on a website discussing CSS image galleries. Can anyone clarify what this code accomplishes? Appreciate it. ...

Enabling individuals to transfer their content to Amazon S3

I have set up an S3 bucket named BUCKET in region BUCKET_REGION. I want to enable users of my web and mobile apps to upload image files to this bucket, with specific restrictions based on Content-Type and Content-Length (specifically, only allowing jpegs u ...

Rotating the camera in first person perspective using Three.js

After struggling to find updated help on first player rotation in three.js, I am facing a challenge where most of the solutions provided are using functions that no longer exist in the current library version. I am attempting to implement a feature where ...

Organize data by month using angularjs

I'm working on an HTML page that displays a categorized list of data for each month. Here's a snippet of how the page looks: July, 2014: Monday 7th Data 7 Data 6 Friday 4th Data 5 Data 4 May, 2014: Sunday 15th Data 3 Thursday 8th Data ...

What Causes the Misalignment Between My Image and Text?

I am trying to randomly select a slide from the list of slides when the page loads, and then display it in the hero section of a website. However, I am facing an issue where the Image seems to be out of sync with the Text & Button (for example, displaying ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...