Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value?

For instance:

angular
.module('app', [])
.controller('CTRL', function($scope) {
    $scope.some_value = {
        instance1: {
            key1: 'value11',
            key2: 'value12'
        },
        instance2: {
            key1: 'value21',
            key2: 'value22'
        },
    };
})
.directive('uiClock', function() {
    return {
        restrict: 'E',
        scope: {},
        template: template,
        link: function(scope, element, attr) {

            // The directive's scope should now contain either the values from instance1 or instance2
            console.log(scope);

        }
    };
});

<div ng-controller="Ctrl">
    <ui-clock ng-bind="some_value.instance1"></ui-clock>
    <ui-clock ng-bind="some_value.instance2"></ui-clock>
</div>

The main goal is to have separate instances of the same directive modify the passed parameter value accordingly.

What do you think about this approach?

Answer №1

It is recommended to utilize the two-way data binding feature.

When creating your directive, make sure to define an isolate scope and use the = syntax, as it can be quite beneficial.

Controller

(function(){

function Controller($scope) {

  $scope.some_value = {
      instance1: {
          key1: 'value11',
          key2: 'value12'
      },
      instance2: {
          key1: 'value21',
          key2: 'value22'
      },
  };

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

Directive

(function(){

  function directive($compile) {
    return {
        restrict: 'E',
        scope: {
          data: '='
        },
        templateUrl: 'template.html',
        link: function(scope, element, attr) {
          var elm = angular.element(element);
          
          Object.keys(scope.data).forEach(function(key){
            scope[key] = scope.data[key];
            elm.attr(key, scope[key]);
          });
          
          elm.removeAttr('data');

          console.log(scope.key1);
          console.log(scope.key2);

        }
    };
  }

angular
  .module('app')
  .directive('directive', directive);

})();

Template

<div>Key 1 : {{key1}}</div>
<div>Key 2 : {{key2}}</div>

You can then call your directive by providing specific data to the isolate scope. Optionally, you can replace the data attribute with the value of the object.

HTML

  <body ng-app='app' ng-controller="ctrl">

    <directive data='some_value.instance1'></directive>
    <directive data='some_value.instance2'></directive>

  </body>

Upon inspection of your directive element, the data attribute will be replaced with attributes like key1 = value...

Check out the Working Plunker.

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 there a way to use JavaScript to modify the position of a div element

Can we adjust the div position using CSS (absolute or relative) with JavaScript? Here's an example code snippet: <div id="podpis" style="margin-top: 2rem;"> <div class="invoice-signature"> <span><?=$xml->sanitiz ...

Is there a way to adjust the font size in Javascript/Html without changing the color?

I have a code snippet that creates a button to increment a variable, and I want to change the font size of the displayed variable. This code is for a game akin to cookie clicker. <div class="game-object"> <script type="text/javascript>"; var c ...

The AJAX request encountered an error while trying to send a POST request to the http://localhost/upload/undefined endpoint. The

I've been scouring the internet and testing for hours, but I'm still unable to identify the source of the error. I could really use some assistance here. I meticulously followed a tutorial on multiple file uploads with drag & drop functionali ...

Tips for keeping a floating action button visible at the bottom of the screen at all times

I am currently utilizing the Material UI framework. I have a floating action button that I would like to display in a specific position on the page without it moving when scrolling, and I am also wondering if this is a common issue. Below is the code sn ...

What is the process for displaying a hidden div using a button?

I'm running into a problem with my project. Here is the code I've been using to hide my div element : @keyframes hideAnimation { to { visibility: hidden; } } To trigger the animation and hide the div after 6 seconds, I have implemented ...

Protractor timeout error triggered following completion of login process

Having an issue with testing the login procedure. Manual login works fine, but during automated tests I am unable to interact with the page after logging in (My page object model consists of three pages: homePage, loginPage, afterLoginPage). The third ex ...

Google maps are failing to display on the page when loading via ajax

When I click a button, I use AJAX to load a page, but the map on the loaded page is not displaying. There are no errors showing up either. I have tried adding initmap() after the ajax load, but it doesn't work. Do I need to bind it somehow? What am I ...

The uploading of a file in NodeJS is not possible as the connection was closed prematurely

When I created a website using nodejs, there was a specific page for uploading images to the server. It worked perfectly fine when tested on my computer. However, upon deploying it to the server, the upload functionality stopped working. Upon checking the ...

Mastering Protractor: Implementing browser.sleep within element.all(locator).each(eachFunction)

I am currently expecting the text of each element to be printed one by one, followed by a sleep, and then the next element's text to be printed. However, what is actually happening is that all the texts are being printed first and then a single brows ...

Can anyone help me with coloring Devanagiri diacritics in ReactJS?

I am currently working on a ReactJS project and I have come across an issue. I would like for the diacritic of a Devanagiri letter to be displayed in a different color than the letter it is attached to. For example: क + ी make की I was wondering ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

Are you prepared for changing DropDowns?

To ensure users make a selection from a specific dropdown menu, I have implemented the following code to trigger an alert if they fail to do so: <script> function checkSelection(){ var sel = document.getElementById(' ...

Mongodb error occurred due to a duplicate key in the collection with the key value set

I need to set up multiple user accounts. The first account creation is successful, but I encounter an error when trying to create a new account: BulkWriteError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: db.users.$friends. ...

AngularJS: splitting the parent <div> into multiple sections every nth element

I have an array of strings in Javascript and I am attempting to use AngularJS to create nested <div> elements. var arr = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"]; My goal is to group every 3 elements together like so. <div class="pare ...

Failed to perform the action using the Angular Post method

Currently, I am exploring the use of Angular with Struts, and I have limited experience with Angular. In my controller (Controller.js), I am utilizing a post method to invoke the action class (CartAction). Despite not encountering any errors while trigge ...

Suggestions for updating the 'begin' and 'finish' variables transmitted through ajax on fullcalendar?

Shown below is the URL to request JSON data via Ajax: '/php/get-events.php?start=2015-05-31&end=2015-06-07&_=1433154089490'. This query will fetch JSON data from 2015-05-31 to 2015-06-07. However, I am looking to retrieve data over a ...

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...

I am leveraging AngularJS to display a modal window with Bootstrap and Spring servlet integration

In my project, I am utilizing AngularJS to display multiple pages. One of these pages contains a smart-table where I showcase the details of "users". When I wish to edit one of the users, I aim to display the edit page as a popup window. Below is an excer ...

Passing all emitted events from Vue 3 child component to its parent - A complete guide

My Vue components are structured as follows: <TopParent> <!-- Listening for events from EventProducer here --> <Child_1> <Child_2> <Child_3> ... <Child_N> <EventProducer /> &l ...

Combining arrays using value comparison in Google Analytics and MongoDB

Help me out, Stack! This job is driving me crazy. Here's what I'm working on: Using the Google Analytics NodeJS SDK, I'm retrieving data about the most visited pages of my website. By leveraging Google's user-friendly URLs (slugs), I se ...