Angular - Triggering actions with ng-hide and ng-show events

Is there a better solution for monitoring hide and show expressions across all elements in my app?

I am aware that I can achieve this by wrapping the show directive with a function that simply returns the argument:

<div ng-show="catchShow(myShowExpr == 42)"></div>

However, I am looking for a more comprehensive approach to monitor all hide/show events on all inputs in my application.

One option could be to override the ngShow and ngHide directives, but this would require reevaluating the expression.

Another possibility is to directly modify the source code, which is relatively simple:

var ngShowDirective = ['$animator', function($animator) {
  return function(scope, element, attr) {
    var animate = $animator(scope, attr);
    scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
      var fn = toBoolean(value) ? 'show' : 'hide';
      animate[fn](element);
      //An additional step could be added:
      element.trigger(fn);
    });
  };
}];

However, this approach may prevent the use of the Google CDN...

Are there any alternative methods that others can suggest for accomplishing this task?

Answer №1

Here is my CoffeeScript solution for creating directives:

createDirective = (isHide) ->
  ['$animator', ($animator) ->
    (scope, element, attr) ->
      animate = $animator(scope, attr)
      last = null
      scope.$watch attr.oaShow, (value) ->
        value = not value if isHide
        action = if value then "show" else "hide"
        if action !== last
          scope.$emit 'elementVisibility', { element, action }
          animate[action] element
        last = action
  ]

App.directive 'oaShow', createDirective(false)
App.directive 'oaHide', createDirective(true)

Now, the CoffeeScript code converted to JavaScript:

var createDirective = function(isHide) {

  return ['$animator', function($animator) {
    return function(scope, element, attr) {

      var animate, last;
      animate = $animator(scope, attr);
      last = null;

      return scope.$watch(attr.oaShow, function(value) {
        var action;
        if (isHide)
          value = !value;

        action = value ? "show" : "hide";

        if (action !== last) {
          scope.$emit('elementVisibility', {
            element: element,
            action: action
          });
          animate[action](element);
        }

        return last = action;
      });
    };
  }];
};

App.directive('oaShow', createDirective(false));
App.directive('oaHide', createDirective(true));

Answer №2

If you want a different approach, you can use the $watch function on the ngShow attribute. However, this method would require implementing it within a directive (especially useful when dealing with show/hide functionality in a custom directive).

scope.$watch attrs.ngShow, (shown) ->
  if shown
    # Execute code when displaying
  else
    # Execute code when hiding

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

NuxtJs: Oops! It looks like NuxtError is not defined in this context

Exploring NuxtJs is new to me. I decided to experiment with how nuxt-link functions by purposely setting up a nuxt-link to a non-existent route in order to trigger the default 404 page. Here's the line of code I added to the pages/index.vue file: < ...

retrieving embedded content from an iframe on Internet Explorer version 7

Need help with iframe content retrieval $('.theiframe').load(function(){ var content = $(this.contentDocument).find('pre').html(); } I'm facing an issue where the iframe content is retrieved properly in FF, Chrome, and IE 8,9 ...

Setting up the Node.js file system for an Ionic project: A step-by-step guide

Seeking a solution to delete a Folder/File on the client side using javascript/jQuery/AngularJS1. After researching, I found that it can be done using Node.js as shown in this Sitepoint link. Now, I am unsure how to integrate Node.js fs(File System) with ...

Modifying the temp variable by assigning a new value to this.value in Javascript

Using a temporary variable, I initialize a THREE.Vector3 which is then passed into the creation of an object. object[i] = new Object(new THREE.Vector3(0,0,0)); Within the Object class, there is a variable called texture that gets assigned the new THREE.V ...

How to correct header alignment in HTML for Google Table

Utilizing the google visualization table to generate a html table, I have successfully fixed the top section of the html using the stuckpart div. This ensures that regardless of how I scroll, the button remains in place. However, I now aim to fix the table ...

When React JS and PHP(Mysql) combine, the error message "records.map is not a function" may appear

What problem am I facing with my code? The issue lies in my JavaScript code while trying to display the JSON array fetched correctly by the PHP file. The JavaScript implementation of JSON in the state is accurate, but an error occurs when attempting to us ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Library for HTML styling in JavaScript

Is there a reliable JavaScript library that can automatically format an HTML code string? I have a string variable containing unformatted HTML and I'm looking for a simple solution to beautify it with just one function call. I checked npmjs.com but co ...

I am experiencing an issue where the onChange event is not being triggered in my React application

I am currently in the process of creating a random football team picker and handling the database on my own. However, I seem to be encountering issues with the inputs. import React, { use, useRef, useState } from "react"; const fetchAll = async ...

Popper.js failing to initialize during page load

After attempting to initialize Popper.js as shown below, I am encountering an issue where nothing is happening. $().ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); Interestingly, when I apply the same code to a button, it w ...

What is the best way to validate a particular class in javascript?

Need help checking if a specific id has a particular class. Unsure of the process? Here's the code snippet where the attempt at checking the id for a specific class is visible within the homeTransition function. function homeTransition() { ...

Automatically Refresh a Div Element Every 5 Seconds Using jQuery's setInterval() Function

My goal is to refresh the left div every 5 seconds using $.ajax to get JSON data and display 4 random elements in that div. However, even though the left div block refreshes, the content remains the same with the same images always showing. view image desc ...

The server receives `/client/:id` in place of the real id

Front-end Development customer.controller("single_customer", function($scope, $http, $routeParams) { $http.get('http://localhost:4000/customer/:id').then (function(data){ // $scope.whichCustomer = $r ...

What is the best way to make changes to elements in an express array?

I have been developing an express application that enables users to manage a list of web projects through various HTTP methods such as get, post, put, and delete. So far, I have successfully implemented the logic for handling get, delete, and post reques ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

What could be the reason for the misalignment between md-menu and md-button when ng-href is included in the button?

Check out the demo by clicking here: http://codepen.io/audiodude/pen/vLyNvw The main distinction between the top and bottom sections lies in the fact that the top section utilizes an md-button with an ng-href attribute, which Angular Material compiles int ...

Transfer information from a server to a client using the fetch API in pure JavaScript

Hey there, I've been working on a mini app that sends a fetch request to the backend and expects some information in return when a button is clicked. However, I'm facing an issue where the fetch call seems successful with a 200 status, but the d ...

The value retrieved by JQuery attr remains constant

Hey everyone, I'm having an issue with getting the ID from a custom attribute using jQuery. When I try to debug, I keep getting the same value each time. I have an HTML table that lists posts from a database using PHP, each with its own specific ID. ...

Does expressJS use the express() function as a global function?

Can anyone confirm if the express() function used in the second statement is a global function? I have searched my project folder but couldn't find its declaration. var express = require('express'); var app = express(); var fs = require("fs ...