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

Unable to store simple HTML file using service worker

I am working on a webpage that displays a message when the user is offline. However, I am facing an issue with my service worker while trying to cache the page. The Chrome console always throws this error: service-worker.js?v=1:1 Uncaught (in promise) D ...

Troubleshooting issues with the delete functionality in a NodeJS CRUD API

I've been struggling to implement the Delete functionality in my nodejs CRUD API for the past couple of days, but I just can't seem to get it right. As I'm still learning, there might be a small detail that I'm overlooking causing this ...

Frame Tweet Integration

Attempting to create an iframe modal with a Twitter share source. <iframe src="https://twitter.com/share" class="tweetFrame"></iframe> The current setup is not functioning properly, resulting in a blank page. Is there a workaround to ensure t ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

Determine the total number of active links on an HTML webpage using F#

Currently, I am working on developing a basic F# function that will be able to count the total number of links present in a given HTML website URL. I understand that this can potentially be achieved by counting the occurrences of the "<a" substrings, b ...

jQuery Ajax consistently returns the data type of an 'object'

I'm currently working on a validation system for a form using Prototype, but I need to integrate a jQuery ajax function to verify if a username already exists in the database. However, I've run into an issue where the value returned by jQuery is ...

Eliminate any unnecessary spaces in the text of a link following the breaking of a word

While working on a navigation menu, I noticed that in large screens the navigation looks fine but in laptop view, the words are breaking up and it's acceptable. However, I want to remove the extra spacing after the text. In the large screen: In the ...

CSS: using syntax to target element by its unique identifier

Check out this guide: I followed the instructions and used an external stylesheet. I added #menu before each CSS item, for example: #menu ul{ font-family: Arial, Verdana; font-size: 14px; margin: 0; padding: 0; list-style: none;} or: #menu ul li{ displ ...

Utilize PHP to select the same checkbox across multiple pages of a form through a post request

I am a newcomer to coding and I am trying to figure out how to automatically select the same check-box that was marked on the first page of my multi-page form. For example, if the user checks the box labeled Red, I want the box on page 2 to be auto-filled ...

Optimizing jQuery scripts by consolidating them to reduce file size

I've created a jQuery script that performs the same task but triggers on different events, including: Page load Dropdown selection change Clicking the swap button Typing in a text field However, I had to write separate scripts for each of these eve ...

Assistance needed in extracting the body content utilizing javascript or jquery

I am looking to swap out the body content of one page with that of another. How can I retrieve the body content from the response text of the second page in order to make this replacement? Please assist me with this. Thank you in advance, Raja ...

Guide to making a sliding animation appear when hovering over a menu using jQuery

I have noticed a common feature on many websites, but I am unsure of how to explain it. At times, there are sliding elements in the navigation, like an arrow under menu items that moves when the user hovers over different links. Here is an example of a s ...

What could be the reason for the absence of definition for 'res'?

As I work on coding a bot using discord.js, I am facing an issue while trying to set up a system where the bot can send a message as long as it is not blacklisted. However, every time I attempt to run the function, I encounter this error message: Reference ...

What is the method for updating the content within a div element?

I am trying to add multiple elements to my content, including an h1 element, an input field, and some buttons. I have written a function to create the h1 and input elements, but when trying to add them to my content div, I encountered an error (TypeError ...

'AngularJS' filtering feature

I am dealing with an array of objects and I need to extract a specific value when a key is passed in the 'filter' function. Despite my best efforts, the controller code snippet provided below returns an undefined response. Can someone please assi ...

Encountering an Unexpected Identifier while trying to adjust the scope within an Angular.js Directive

Within Angular.js, I am attempting to update a $scope value located in my controller using a directive with two-way binding "=" functionality. The goal is for the directive to update the scope variable. However, I am encountering an error message stating ...

What is the best way to customize the text in the navigation bar at the top of the page

I'm having trouble with the Navigation Bar code in my header. The text is not staying within the header and I can't seem to fix it. Is there a CSS solution to keep the text contained within the header? <div class="header"> <img src= ...

Storing raw HTML in a Mysql database, then fetching and displaying it on a webpage

I'm having an issue with my application. It's a form builder that allows users to create their own forms and then save them for later use. The HTML code generated by the form builder is stored in a MySQL database. However, when I try to retrieve ...

How can you use the transform property in CSS to rotate the dropdown arrow by 180 degrees and move it vertically by 2 pixels?

gradeexpanded:false, gradeOnClick: function (event) { this.gradeexpanded = !this.gradeexpanded; }, .dropdown-check-list { margin-left: 35px; displa ...

Sending data to API using AngularJS Http Post

Upon clicking "Add new User", a modal pop-up will appear with a form containing a text field and a checkbox. However, upon clicking the create button, the data is not being posted to the API and the modal pop-up remains open without closing. I would like ...