What is the best way to retrieve scope variables from multiple directives?

I am working on a directive that represents a person with changing location attributes. My goal is to access all the locations together and plot them on a map using the angular-leaflet-directive. I'm struggling to figure out how to access these variables in one place. Although I feel like I'm close to getting it working, I'm unsure which scope has access to all the directive's variables. Here is what I have so far:

Index.html

<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset=utf-8 />
<title></title>

  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="http://code.angularjs.org/1.2.0-rc.3/angular.min.js"></script>
  <script src="http://code.angularjs.org/1.2.0-rc.3/angular-resource.min.js"></script>
  <script src="http://code.angularjs.org/1.2.0-rc.3/angular-animate.min.js"></script>
  <script src="app.js"></script>

</head>

<body ng-controller='MainCtrl'>

  <a href='' class='btn' ng-click='addPerson()'>Add new person</a><Hr>

  <div id='people'>
    <person lat="0.0" lng="0.0"></person>
    <person lat="0.0" lng="0.0"></person>
    <person lat="0.0" lng="0.0"></person>
  </div>
  <hr>

  <div class="map"> <!-- this will be a directive representing a map -->
      How do I access the lat and lon of each directive here? So I can plot them all on a map (which is also a directive ...)
  </div>

</body>

</html>

App.js

var app = angular.module('app', []);

app.directive('person', function ($compile, $timeout) {

    function link ($scope, elem, attrs, ctrl) {     

        $scope.lat  = attrs.lat;
        $scope.lng  = attrs.lng;


        $timeout( function changePosition() {

            console.log('Changing position ...');
            $scope.lat  = Math.random()
            $scope.lng  = Math.random()

            $timeout(changePosition, 2000);
        }, 2000);
    }

    return {
      restrict: 'E',
      replace: true,
      template: "<span>Current Lat={{lat | number:2}}, Lng={{lng | number:2}}<br><br></span>",
      link : link,
      scope: {},
    }

});

app.controller('MainCtrl', function ($scope, $compile) {

    $scope.addPerson = function() {
            console.log('Adding new person');
            var lat  = Math.random()
            var lng  = Math.random()
            angular.element('#people').append($compile('<person lat="'+lat+'" lng="'+lng+'"></person>')($scope));
    }


});

Answer №1

To make those variables accessible in the link function of your directive, you simply need to define them in the scope section of the directive. This way, you can use them just like you would in a controller.

app.directive('person', function ($compile, $timeout) {

function link($scope, elem, attrs, ctrl) {     

    $timeout(function changePosition() {

        console.log('Changing position ...');
        $scope.lat = Math.random();
        $scope.lng = Math.random();

        $timeout(changePosition, 2000);
    }, 2000);
}

return {
  restrict: 'E',
  replace: true,
  template: "<span>Current Lat={{lat | number:2}}, Lng={{lng | number:2}}<br><br></span>",
  link: link,
  scope: {
      'lat': '=',
      'long': '='
  },
}

})

If you want to understand how scope variables operate within directives, check out this resource.

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

Is it possible to include personalized validations in Formik's YupValidationSchema?

Is it possible to include custom validations in Formik's YupValidationSchema as shown below? YupValidationSchema = () => { return Yup.object({ Email: Yup.string() .max(256, "Length exceed 256 chars") ...

Is there a way to display the button solely when the cursor is hovering over the color?

When I hover over a particular color, I want the button to show up. However, instead of displaying the button only for that color, it appears for all the colors of the product. Also, the placement of the button on the left side means that if I try to hover ...

Changing the color of a Highcharts series bar according to its value

Playing around with Highcharts in this plunker has led me to wonder if it's possible to dynamically set the color of a bar based on its value. In my current setup, I have 5 bars that change values between 0 and 100 at intervals. I'd like the colo ...

Adjusting the StrokeWidth in pixels/em units on fabricjs

When adding a rectangle or circle to the canvas and adjusting the strokeWidth using a range input, how can we determine the value of strokeWidth in pixels, em, or percent? For instance, if we set strokeWidth to 5 within a range of 1-10, how much does the a ...

Is each individual character displayed on the web page twice when using a controlled component?

Currently, I am diving into the extensive React documentation. A particular section caught my attention - controlled components. It delves into how form elements, such as an <input>, manage their own internal state. The recommendation is to utilize c ...

Utilizing HTML5 history instead of hash URLs to preserve the user's browsing history

Our application is a single page that dynamically loads results based on query strings. The query string format we use is as follows: ?city=Delhi&pn=1 Within the SPA, there are different sections displayed on the same page. As users navigate through ...

Avoiding duplication when using LoopbackJS and the AngularJS SDK to save models is important

I am working with LoopBackJS AngularJS SDK and have a model for sites (id(pk) integer, name varchar(50), url varchar(100)). However, when I attempt to update the name field and call site.save(), the record ends up being duplicated. If I try to update any ...

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...

Issues with setting headers after they have been sent - Can you explain why?

How am I setting a header after it has been sent to the client? Here is the code snippet: When a form is submitted, a post ajax request is triggered which returns a JSON object to the client. I have commented out most of the code to troubleshoot, and cur ...

An issue with JSPDF arises when used on mobile devices

Currently, I am working on a project to create a responsive web application, which involves utilizing JSPDF for generating PDF reports directly from HTML. For a demonstration of the functionality, you can check out this Demo. Unfortunately, when trying t ...

What could be the reason Angular is not refreshing with a JSON file update?

Having trouble using a basic Angular JS app to load data from a JSON file onto a website. The JSON file contains: {"a": "a"} The Angular application setup is as follows: var app = angular.module("app", []) .controller("ctrl", ["ser", function(ser) { ...

Having trouble launching Cypress on my Mac - stating that it cannot find Cypress

Despite searching through multiple answers on S.O, none of them have solved my issue. To better explain my question, I've created a video. You can view it here Everything was working perfectly just yesterday, so what could have possibly gone wrong? ...

Having trouble hiding the message "Not found" with ng-hide and filters in AngularJS

I am currently working on incorporating instant search functionality with filters in AngularJS. My goal is to have the "Not Found!!" message displayed when the filter results in an empty array, indicating that no matches were found. However, I have encou ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

Guide to iterating through an array within an object in Vue.js

Can someone help me with looping through data fetched from an API using a GET request in Vue.js? This is the sample response obtained: "data": { "Orders": [ { "OrderID": 1, "Ordered_Products": { ...

Error: JSON parsing stopped due to unexpected end of file while attempting to parse data

After testing with other APIs successfully, I found that this particular one is not functioning as expected. const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ...

What is the best way to showcase my React App.js in an HTML document?

Is there a way to display my React app file (App.Js) within my Index.html file? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/fav ...

Clicking on a JQuery element triggers an AJAX function, although the outcome is not aligned with the intended

Instead of using a fiddle for this task, I decided to work on it online since my knowledge of fiddles is limited. However, after multiple attempts and hours spent rewriting the code, I still can't get it right. The issue at hand requires that when cl ...

Find out the keycode of an event in ReactJS when a key is released

Whenever I try to get keyCode on a keyUp event, it always returns 0. Why is this happening? I want to avoid using keypress and similar methods, and I also need to utilize an arrow function: handleKeyPress = (e, type) => { let KeyCode = e.charCode; ...

Create a duplicate <li> element and animate it using jQuery

Here are the list items: <ul> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</l ...