Exploring Scope Data Using a Custom AngularJS Directive

We are completely new to the world of AngularJS and are currently facing a challenge in displaying HTML tooltips from a custom directive within Angular. As beginners in this technology, we are struggling to find the right solution for this issue.

Initially, we had a working version of the solution using Angular with Web API. However, we realized that the mouseover events and CRUD functionality should be handled in directives rather than the controller. So, we are now extracting that code and rebuilding it.

Right now, in a Plunker Proof of Concept (POC), we have:

  1. Loaded a very small SVG file.
  2. Loaded a small JSON data file.
  3. Attached a custom directive hover event to each SVG element.
  4. When a specific element is hovered over, an alert() displays the element's ID.

Sample SVG:

<g id="f3s362c16">
<rect x="577.5" y="533.2" fill="none" width="22.2" height="25.7"/>
<polyline fill="none" stroke="#CEDEED" stroke-width="0.6468" stroke-miterlimit="10" points="590.4,559 577.5,559 577.5,533.2 
    599.5,533.2 599.5,550   "/>
<text transform="matrix(1 0 0 1 590.9561 557.4941)" font-family="arial, sans-serif" font-size="5.1408">362.16</text>

JSON Sample:

{"Id":1,"empNum":null,"fName":" Bun E.","lName":"Carlos","refacName":null,"deptId":"Drums","divisionId":null,"jobDesc":"Drummer","seatTypeId":1,"officeCode":null,"phone":null,"seatId":"f3s362c12 ","oldSeatId":null,"floor":3,"section":"313 ","seat":"12 "}

We have defined a scope variable "empData" for the JSON data in the HTML file:

{{ **empData** }}

Data loading in the controller file:

 var onLoadComplete = function (response) {
   $scope.**empData** = response.data;
 }

 //error
 var onError = function(reason) {
   $scope.error = "Could not get the data";
 }

 //get data
 $http.get('data.json')
    .then(onLoadComplete, onError);

Directive to load SVG and add directive to cube element

//directive loads SVG into DOM
angular.module('FFPA').directive('svgFloorplan', ['$compile', function ($compile) {
return {
    restrict: 'A',

    templateUrl: 'test.svg',
    link: function (scope, element, attrs) {

        var groups = element[0].querySelectorAll("g[id^='f3']")
        angular.forEach(groups, function (g,key) {
            var cubeElement = angular.element(g);
            //Wrap the cube DOM element as an Angular jqLite element.
            cubeElement.attr("cubehvr", "");
            $compile(cubeElement)(scope);
        })
      }
    }
}]);

Cube Hover Directive:

angular.module("FFPA").directive('cubehvr', ['$compile', function ($compile) {
return {
    restrict: 'A',
    scope: true,
    empData: "=",

    link: function (scope, element, attrs) {...}
        });

At this point, we're stuck on how to access the view/page scope variable {{empData}} in the hover directive since we're already passing information to the cubeHvr directive:

angular.module("FFPA").directive('cubehvr', ['$compile', function ($compile)       {...}      

Any guidance or assistance you can provide would be greatly appreciated. Thank you.

Answer №1

Describe a service using the code snippet below:

angular.module('FFPA')
.service('dataService', function () {
    this.getData = function(){
        return $http.get('data.json').then(function(){
             return response.data;
           }, function(){
               return {err:"Could not fetch the data"};
           }
        );
    }
});

Utilize this service by injecting it into any directive, controller, component, or another service.

angular.module("FFPA").directive('cubehvr', ['$compile','dataService', function ($compile,dataService) {
return {
    restrict: 'A',
    scope: true,
    link: function (scope, element, attrs) {

        dataService.getData().then(function(data){
            scope.emData=data;
        })

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

I've encountered a peculiar error that is new to me while using bootstrap and javascript. Can anyone shed light on what this error signifies?

Hey there! I've come across this error in the console while attempting to utilize Bootstrap. It seems that a style is being refused from 'http://127.0.0.1:5500/node_modules/font-awesome/css/font-awesome.min.css' due to its MIME type ('t ...

Display a loading dialog for several asynchronous requests being made via AJAX

When making two asynchronous ajax calls, a loading dialog box is displayed for each call using the code below: jQuery('#msg_writter').show(); After a successful request, the loading dialog is hidden with the following code: jQuery('#msg_w ...

Dispatch prop within useEffect

App.js -> <Lobbies inGame={inGame} setLobby={setLobby} userName={userName} userKey={userKey}/> Lobbies.js -> import React, { useState, useEffect } from 'react'; import firebase from 'firebase'; const Lobby = ({userKey, ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Updating ngModel value dynamically from controller

I have been trying to update the value of an ngModel variable from my controller, but it doesn't seem to be reflecting in the views. Despite looking at other solutions on SO, nothing has worked for me so far. I am looking for a solution that doesn&apo ...

Displaying a random div using javascript

Seeking a way to display random divs on my webpage, I came across a stackoverflow solution: Showing random divs using Jquery The recommended code can be found here: http://jsfiddle.net/nick_craver/RJMhT/ Despite following the provided instructions, I am ...

Step-by-step guide on how to include the "content-based-recommender" package in a Reactjs project

I recently started learning React.js and I'm interested in using the "Content-Based Recommender" package from npm. However, after downloading it, I encountered an issue with importing it. The documentation suggests the following: const ContentBasedRec ...

What is the best way to validate if fields are blank before sending a message using the button?

<template> <div> <div class="form-group"> <label for="name">First Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Ente ...

How to Pause or Temporarily Halt in Jquery?

Looking to lift the object up, wait 1000ms, and then hide it. I found this snippet of code: $("#test").animate({"top":"-=80px"},1500) .animate({"top":"-=0px"},1000) .animate({"opacity":"0"},500); However, using ".animate({"to ...

AngularJS directive's watch function is returning undefined values for both the newValue and oldValue

My goal is to create an alert system using a directive. I am using a service to manage all the alerts in my application, and a directive to display them. I have implemented a watch in the directive to apply a timeout for alerts that should disappear automa ...

Trouble with refreshing view - angular, firebase

I've been struggling with getting this function to fire more than once, even though it should update when scope.job.getApplicants() changes. I've tried various methods like $watch, $apply, and firebase's ref.on('value', but nothing ...

Embed programming into an iframe upon its loading

I am looking to enhance the functionality of an iframe by injecting HTML and JavaScript code into it upon loading. The goal is to enable users to navigate through different links within the iframe while they are browsing. Here is what I have attempted so ...

substituting symbols with colorful divs

I'm looking to add some color to my text using specific symbols. (), ||, and ++ are the symbols I'm using. If a text is enclosed in | symbols, it will appear in blue, and so on... Here is the code in action: const text = "|Working on the| i ...

Is there a way to bypass the final function call when using Express Middleware?

In my Node.js project using express, I have a function inside a get route... The function currently includes a simple caching functionality that I coded myself. It queries data from an MSSQL Database and returns it using res.json(data). However, I want to ...

When retrieving the card in React, only the first element is affected by the .map function

There seems to be an issue with Arrays.map as it is only working for the first object in the array. Here is the main function: function App(){ return ( <div> <NavBar /> { data.map((prop) =&g ...

Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately ...

Is it permissible to utilize Factory service functions within the factory service itself?

Let's consider a factory service where we can access and modify the firstname of a user. app.factory('userService',['$rootScope',function($rootScope){ var user = {}; return { getFirstname : function () { ...

Utilizing a d.ts Typescript Definition file for enhanced javascript intellisene within projects not using Typescript

I am currently working on a TypeScript project where I have set "declaration": true in tsconfig.json to generate a d.ts file. The generated d.ts file looks like this: /// <reference types="jquery" /> declare class KatApp implements IKatApp ...

Best practice for organizing sort icons in a table with React and MaterialUI

I am currently implementing the following code in a tsx component. I am still learning about the various layout options available. You can view my code on this sandbox link. import React from "react"; import { ArrowDropUp, ArrowDropDown } from "@materia ...

Not every time you call the AngularJS run method does it actually execute

Working on a simple Angular app, I wanted to implement a user login check and redirection. However, I encountered an issue where accessing the home page from the form site resulted in inconsistent behavior - sometimes redirecting and other times showing ...