What is the correct way to run javascript on a DOM element when ng-show is triggered?

For those who prefer shorter explanations, there's a TLDR at the end. Otherwise, here's a detailed breakdown.

I have a form that consists of multiple inputs organized into different "pages" using ng-show.

What I aim to achieve is when ng-show reveals a new "page" and hides the previous one, to trigger javascript to add a class, focus on specific input element within the new page. This way, the user knows exactly what action to take next on this newly displayed page.

I've been experimenting with using a $watch function, but it seems like I might be overcomplicating things and potentially missing out on a simpler solution. Additionally, I'm having trouble getting it to work as intended.

Each page contains various divs such as questions, instructions, or input fields. However, upon making a page visible, there is a particular div that I wish to highlight (referencing myFocusDirective placement), as not all divs are interactive for users. Here's an example of how the pages are structured:

<div id="page1" ng-show="isPage(1)">
    <div>
        Text
    </div>
    <div myFocusDirective>
        <input>
    </div> 
</div>

<div id="page2" ng-show="isPage(2)">
    <div myFocusDirective>
        <button>
    </div>
</div>

I've attempted different approaches like watching attributes or using $timeout, but haven't been able to accurately identify when ng-show is triggered. My understanding leads me to believe that it should simply apply "ng-hide" to switch classes in the div, yet I am struggling to make this comparison...

scope.$watch(function() { return element.attr('class'); }, function(newValue) {
    if (newValue.match(/ng-hide/g) === null && newValue.match(/highlight/g) === null && newValue.match(/complete/g) === null) {
         highlightAndFocus(element[0]);
    }
},true);

I also tried using $timeout on the attrs, but encountered issues due to multiple matches resulting from classes being applied to several divs.

scope.$watch(attr.initial, function(newValue) {
    $timeout(function() {
        highlightAndFocus(element[0]);
    });
},true);

Any assistance would be highly appreciated, as I feel like I may be overlooking something crucial.

TLDR; Following ng-show activation, I want to adjust div classes and then focus on an input field within the div.

Answer №1

Why not simplify your life by transferring the ng-show content to your div as well:

<div id="page2" ng-show="isPage(2)">
    <div myFocusDirective focuson="isPage(2)">
        <button>
    </div>
</div>

Then, monitor the focuson in your directive scope? This way, you won't need to worry about parent classes.


Moreover, if you are tracking an attr, it is recommended to use attr.$observe

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 could be the reason why my AJAX error is not displaying the exception from my Webmethod?

I am currently utilizing Google Chrome for my work tasks. After referring to , I attempted to throw an exception from a webmethod. However, no output is shown in the console.log. The only information I received is a generic error message from the network ...

The functionality of Vue.js checkboxes is not compatible with a model that utilizes Laravel SparkForm

I've configured the checkboxes as shown below: <label v-for="service in team.services"> <input type="checkbox" v-model="form.services" :id="service.name" :value="service.id"/> </label> Although they are displayed correctly, the ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

jQuery efficiently handles large amounts of text data transfer (gradual loading)

The issue at hand: My website relies on jQuery AJAX (post) for navigation, meaning the page doesn't refresh every time a user moves to a different section. This setup requires me to fetch data using AJAX and present it dynamically. While this works w ...

Labeling src library files with namespaces

I have developed a ReactJS website that interacts with a library called analyzejs which was created in another programming language. While I am able to call functions from this library, I do not have much flexibility to modify its contents. Up until now, ...

Angular 2 event emitter falling behind schedule

I am currently utilizing Angular 2 beta 6. The custom event I created is not being captured import {Component, OnInit, EventEmitter} from 'angular2/core'; import {NgForm} from 'angular2/common'; import {Output} from "angular2/core" ...

The color of the text changes from its default color when not in use

Hey there, let me break this down for you... I'm currently in the process of styling a contact form. I've managed to change the text color of my input focus to white. However, when I click away from the form, the inputted text color reverts ba ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

Guide to creating a synchronous wrapper for jQuery ajax methods

I've made the decision to switch from synchronous ajax calls to asynchronous ones due to lack of support in most modern browsers. My code is currently reliant on synchronous (and dynamic) ajax calls to client-side functions that must be completed befo ...

Is there a parameter I am overlooking when trying to remove an item from a state-stored array using the delete button at line 55?

Need help with the code in the app component. I know it's not ideal, any assistance would be greatly appreciated. I'm a bit lost and can't figure out how to remove an item from the list after it has been added. Everything else seems to work ...

The second JSP page fails to load following an AJAX POST request

The following code snippet is found in page1.jsp. $.ajax({ type: "post", url: "page2.jsp", data: newdata, success:function(msg){ return msg; } ...

What is the solution to the error "modal is not defined" in Vue.js?

Hey guys, I need some help with an error that popped up: [Vue warn]: Error in v-on handler: "TypeError: $(...).modal is not a function". The issue is with the modal function Below is the code snippet from my welcome.blade.php: <body> &l ...

Add a distinctive tooltip to the final element in a table row within a loop using JQuery

My challenge involves appending unique tooltips to the last item in a row of data, where each tooltip is specific to that particular row. However, when I add a new tooltip for the latest item, it ends up replacing the tooltips from previous rows. The desi ...

Apologies, but it seems there was an issue reading the "checked" property as it is null

I am currently facing an issue with the submit button in my Django application. It appears that the Javascript function is unable to determine which checkboxes are checked, as all I see in the console logs are "cannot read properties of null, reading "chec ...

Troubles with Installing CRA and NextJS via NPM (Issue: Failure to locate package "@babel/core" on npm registry)

Summary: Too Long; Didn't Read The commands below all fail with a similar error message... Couldn't find package "@babel/core" on the "npm" registry create-react-app test npm install --save next yarn add next Details of Running create-re ...

NodeJS: Issue when implementing try/catch with async/await causing SyntaxError

As a newcomer to Node Js, I am struggling to understand why the code below is throwing a syntax error with catch(). I recently updated to Node JS V14. Any assistance would be greatly appreciated. async function demoPromise() { try { let message ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...

Intermittent issues with requesting JSON data

My current project involves building a script that iterates through a list, retrieves product SKUs, and includes them in a JSONP request to retrieve an object. The script seems to be functioning as intended, but there are occasional failures. Here is an e ...

Guide on submitting a reply to Harvard's "Guess my Word" challenge using JSoup

I am currently working on developing a bot to enhance my gameplay in Harvard's intriguing "Guess my Word!" game. After some exploration, I found out about a post request feature available through Chrome's "inspect element" functionality when a pl ...

AngularJS templateUrl changes on page refresh``

I am currently using an angular packet template that consists of 11 pages, each with a corresponding button. The route code for this template is as follows: state('app.pagelayouts.fixedsidebar1', { url: "/fixed-sidebar", templateUrl: "assets ...