Access the scope property from a separate isolated scope by utilizing a single directive

Essentially, I am facing an issue with a directive that is utilized by two different forms. When the page loads, each form displays the default properties provided by the directive. The challenge arises when both forms require a checkbox option to apply these properties to the other form as well. Each form has its own HTML template and controller.

return function row(ModelService) {
  return {
    restrict: 'E',
    templateUrl: function(elem, attr) {
      return elem.templateUrl;
    },
    scope: {
      formTitle: '@',
      type: '@'
    },
    link: function(scope, elem) {

      scope.setDefault = function() {
        .
        . settings for scope defined here
        .
        .
        .
      }
      
      scope.close = function (action) {
        .
        . if(checked) {
        .   code to apply settings to the other form 
        . }
        .
        .
        .
      }
    };
  });
<div ng-controller="app.FirstCtrl">
  <propFilter form title="someTitle" template-url="someUrl"></propFilter>
  . 
  . multiple div elements with ng-model
  .
  .
  .
  <input id="applyToOther" type="checkbox">
</div>


<div ng-controller="app.secondCtrl">
  <propFilter form title="someTitle" template-url="someUrl"></propFilter>
  .
  . multiple div elements with ng-model
  .
  .
  .
  <input id="applyToOther" type="checkbox">
</div>

I am seeking guidance on how to replicate the properties of one scope onto another using the same directive, if possible. Any assistance would be greatly appreciated. Thank you!

Answer №1

If you want to centralize your common data, one approach is to create a factory for that purpose. You can then inject this factory into controllers or directives based on your specific requirements.

Here is an example demonstrating this concept:

HTML:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-app="directiveBroadcast">
  <div ng-controller="directiveCtrl1 as ctrl1">    
    <checkboxes ng-model="ctrl1.checkboxData"></checkboxes>
  </div>
  <div ng-controller="directiveCtrl2 as ctrl2">
    <checkboxes ng-model="ctrl2.checkboxData"></checkboxes>
  </div>

<script type="text/ng-template" id="/directive.html">
  <div>Directive</div>  
  <input type="checkbox" ng-model="ngModel.checkbox1" />
  <input type="checkbox" ng-model="ngModel.checkbox2" />
</script>
</body>
</html>

JS:

angular.module('directiveBroadcast', [])
.factory('checkboxData', function() {
  return {checkbox1 : true,
          checkbox2 : false
         };
})
.controller('directiveCtrl1', function(checkboxData){
  this.checkboxData = checkboxData;            
})
.controller('directiveCtrl2',function(checkboxData){
  this.checkboxData = checkboxData;            
})
.directive("checkboxes", function() {
  return {
    restrict: "E",
    scope: {
      ngModel: "="      
    },
    templateUrl: "/directive.html"    
  };
});

Another option would be to inject the common data directly into the directive or utilize a "static" context within the directive.

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

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

Develop various Checkboxes using JavaScript

I am attempting to dynamically create multiple checkboxes using JavaScript. I have written the following code: var response= data; var container = document.createElement('div'); var checkboxContainer = document.createElement(&apo ...

A guide on utilizing the index column for multiple tables using just one statement in the datatable js library

I've incorporated the datatable js for managing two tables on a single page. HTML <!-- Table#1 --> <table class="dataTable"> <thead> <tr> <td>#</td> <td>col1</td> </tr> &l ...

Navigating to a new address using ajax and express routing

I am facing an issue with a button having an ID of 'tune-in' on a page named auth.ejs. The button is supposed to navigate to a new page called index.ejs when clicked. However, instead of rendering the index page, clicking the button keeps me on ...

Removing a child node in a JSON data structure

I am dealing with the following JSON data. My goal is to remove only the children nodes from the array while keeping the rest of the content intact. { "model_type_name": "portfolio", "hier_model_type_name": "portfolio", "object_type": "product", "gen_new_ ...

Tips for saving all models retrieved using the `DB.find({})` method in Mongoose

Is it possible to edit values in an array of query results returned from the database? We know that we can use model.save() for a single Query/row, but what about multiple Query results in an array? How can we achieve this? Would something like the follo ...

What is the proper way to display an Angular variable from the controller in HTML?

I am seeking guidance on how to incorporate variables set in my controller into an HTML tag. For instance: <div class="container" ng-class="{ 'custom-class': isActive }"> The ng-class directive requires a variable. In my controller, I ha ...

What impact does turning off Javascript have on ASP.NET?

There seems to be varying accounts of the impact of turning off JavaScript on ASP.NET applications. Some say it works fine, others claim only certain parts are affected, while some suggest that nothing functions at all. I am curious to know specifically h ...

The Videojs controls are unresponsive to clicks

Having a strange issue with videojs. I've been attempting to load videojs in the same way as outlined in the documentation, using a dynamic video tag. videojs(document.getElementById('myVideo'), { "controls": true, "autoplay": false, "prelo ...

Node.JS: Combining Multiple Files into a Single Output File

Currently, I am in the process of building a data pipeline using Node.js. While I acknowledge that there are better ways to approach this, I am determined to implement it and make improvements as I go. Here's the scenario: I have a collection of gzi ...

Determining the browser width's pixel value to enhance responsiveness in design

Lately, I've been delving into the world of responsive design and trying to grasp the most effective strategies. From what I've gathered, focusing on content-driven breakpoints rather than device-specific ones is key. One thing that would greatl ...

Node.js: Passing a URL as a Parameter

Snippet: app.get("/:url", function(req,res) { var url = req.params.url; res.send(url); }); Issue: The provided code snippet is not functioning as expected. When attempting to access: http://localhost:3000/https://www.google.com An error messa ...

Vue-Router functions only on specific routes

While my vue-router correctly routes the URL for all menu buttons, it's not displaying each Vue component properly. You can see a demonstration here. Here is a snippet of my HTML (using Vuefy) <div class="navbar-start"> <a ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

Best Practices for Validating Confirmed Passwords in AngularJS Component

Check out the JavaScript file snippet below .component("password", { require: {ngModelCtrl: 'ngModel'}, template: '<input type="{{$ctrl.type}}" class="{{$ctrl.classname}}" placeHolder="{{$ctrl.placeholder}}" name="{{$ctrl.name}}" ng-requ ...

Using an if/else statement to detect if the iFrame is devoid of content

I have a customized youtube video section on my website template that can display either an embedded video or an image based on client preference. Currently, I am trying to implement code that will detect if the youtube video source is empty and then displ ...

Unusual problem detected with scrolling fixed div upwards

I have encountered a peculiar issue while attempting to fix a div containing other nested divs. My goal is to have the .menu div remain visible and fixed at the top of the page while scrolling, hiding the .slideshow_head div. However, despite fixing the . ...

Using jQuery .css({}) is not causing negative margin to function as expected

$('#thankYouMessage').css({"height": textHeight, "margin-top:": "-52px", "padding-left": "19px"}); The CSS property 'padding-left:' will be applied as expected, but the negative margin will not take effect. The 'margin-top:' ...

After an Ajax request, the functionality of Javascript/Jquery ceases to work

After successfully submitting a form via ajax for the first time, the subsequent submissions seem to break all javascript functionality on the page. Additionally, the form is unable to submit with ajax again. Below is the code snippet for the ajax call: ...