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

Tracking accurate responses with button click

In my quiz, I want to keep track of the correct answers selected by the player. When a player clicks on the correct answer, the counter should increase by one. At the end of the quiz, the HTML should display a message like "You got" + correct + "answers co ...

Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows: "Today is Sunday, the 31st day of March in the year 2019." I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on ...

Exploring the functionalities of command line arguments in Vue.js

Is there a way to set command line arguments for a Vue.js application? I am utilizing Vue 3 on the frontend which interacts with a Python backend (Flask) using Axios. Currently, I am defining the baseURL for Axios in my main.js file as follows: import axio ...

How can I retrieve an array of collections from multiple parent documents in Firebase and pass them as props in Next.js?

I need to access all the collections within the documents stored in a collection named users. This is how I currently retrieve all the user information: export async function getServerSideProps() { const snapshot = await firebase .firestore() .collection ...

Significant issue identified with ajax functionality, requiring immediate attention

After executing the code in the console, I expected to see the ajax object with a readyState of 0 (as I aborted the ajax call). However, Chrome is displaying the number 4 in the console instead of 0. This discrepancy is surprising. http://jsfiddle.net/8yC ...

Numerous occurrences of Setinterval

I am currently facing a minor issue with my code. My setup involves an auto-playing rotating fadeIn fadeOut slider, where clicking on a li will navigate to that 'slide' and pause the slider for a specific duration. The problem arises when a use ...

Generate a compressed folder containing a collection of PNG images

While attempting to generate a zip file using JSZip, I encounter issues where the images are falsely flagged as not being instances of Blob or the final result turns out to be corrupt and cannot be extracted. The process involves an API on the back-end th ...

AngularJS with ui-router for creating a lightbox overlay with the added functionality of deep linking

Exploring the implementation of AngularJS for creating a lightbox with URL deeplinks. The functionality works smoothly, however, assigning a name to it for every page along with the corresponding template is essential. To achieve this, I am utilizing ui-r ...

Exploring the interaction of karma, jasmine, Angular, and UI router through testing the resolve function when using state.go with parameters

In my Angular module "moduleB", I have the state defined as shown below: $stateProvider .state('stateB', { parent: 'stateA', abstract: true, templateUrl : base ...

Having trouble with the Tap to copy discount code function not working in the Shopify cart drawer?

Our goal is to implement tap to copy functionality for code snippets on our Shopify website. It works seamlessly on the product detail page, but in the cart drawer, it only functions properly after the second page load. {% if cart.total_price > 0 % ...

Transition smoothly between sections using fullPage.js with clipping path effects

I am looking to create a unique clipping animation utilizing SVG clipping path. The animation should hide the first section while revealing the second section in a smooth transition using fullPage.js. This idea is somewhat similar to the question discusse ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Obtain Page Parameters within a Nested Next.js Layout using App Router

My Next.js App Router has a nested dynamic page structure using catchall routes configured like this: app/stay/ |__[...category] | |__page.js |__[uid] | |__page.js |__layout.js Within the 'layout.js' file, there is a con ...

What is the best way to incorporate an AngularJs theme into Django?

My experience in AngularJS and Django is at a beginner level, but I am eager to develop a web application using both platforms along with Postgre SQL as the database. I have a specific AngularJS theme that I would like to seamlessly integrate with my Dja ...

combine various types of wrappers in React

We're embarking on a fresh project with React, and we will be utilizing: React Context API i18n (react.i18next) GraphQL (Apollo client) Redux CSS-in-JS (styled-components or aphrodite) The challenge lies in each of these implementations wrapping a ...

Utilize AJAX to connect to a remote domain from an extension

I am currently working on creating a Chrome extension that will utilize AJAX to fetch data from a specific webpage and then generate notifications based on the content of that page. The webpage I am targeting is a ticketing system, and my goal is to deter ...

Toggle checkbox feature in Bootstrap not functioning properly when placed within ng-view

When attempting to embed a bootstrap toggle checkbox within <ng-view></ng-view>, an issue arises where a regular HTML checkbox is displayed instead of the expected bootstrap toggle. Strangely, the same checkbox functions as a bootstrap toggle w ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...