Implement the use of `require` to update the `$watch` in an

As a new Angular user, I am facing an issue that involves having two directives in my HTML code like this:

<parent-dir param="par">
   <child-dir></child-dir>
</parent-dir>

And defining them in my JavaScript code as follows:

In the parent directive:

app.directive('parentDir', function(){
return {
 restrict: 'E',
 scope: {
 param: '='
  }
 }
})

And in the child directive:

app.directive('childDir', function(){
return {
 restrict: 'E',
 require: '^parentDir',
 controller: function($scope, $element){
  <-- SHOULD I PUT WATCHER HERE -->
  },
 link: function(scope, element, attrs, parentdirCtrl){
  <-- SHOULD I PUT WATCHER HERE -->
  }
 }
})

I'm unsure about where to place an optional $watch in the child directive in order to track all changes in the param model. While using $watch in the parent controller reflects all changes on the param in the parent directive, I'm struggling to pass this information to the child directive.

Answer №1

To ensure proper functionality, the code should be placed inside the link function which has access to the parent controller through the 4th parameter of the link function called parentdirCtrl. This eliminates concerns about the params variable as it utilizes two-way binding (=) within the directive to update values in both the parent controller's scope and the directive's scope. It is also important to define a controller in the parentDir directive so that the scope of the parentDir directive is shared with the childDir.

Code

app.directive('childDir', function() {
  return {
    restrict: 'E',
    require: '^parentDir',
    template: '<div class="test">INner {{param}}</div>',
    controller: function($scope, $element) {
    },
    link: function(scope, element, attrs, parentdirCtrl) {
      scope.$watch('param', function(newVal, oldVal) {
        console.log(newVal);
      }) //true only if its object.
    }
  }
})

Demo Plunkr

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

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

Issue accessing object property in Handlebars template with ExpressJs

Personalized Routes: router.use(function(req, res, next) { res.locals.currentUser = req.user; next(); }); /* Accessing the home page. */ router.get('/', function(req, res, next) { console.log(res.locals.currentUser.username); ==>> t ...

Creating an input range element and its event handler dynamically within the ajaxStop function allows for real-time updates based on the

As a beginner in JavaScript development and Ajax, I am currently working on creating a webpage that utilizes Ajax to fetch data from a server. The data is then used to draw geoJSON features on a map using Leaflet. These feature sets need to be toggleable f ...

Submit Button Field - HTML ButtonFor

Being relatively new to MVC Razor and web development, both front-end and back-end, I'm in need of a button that can send a stored value to the controller/model. I attempted to mimic the functionality of Html.TextBoxFor by giving it attributes similar ...

Tips on avoiding a div from causing its parent's mousemove event to activate if it is concealed

I have a collection of media content with a set of controls positioned above it. I am attempting to implement functionality where the controls will disappear when the user's mouse is inactive and reappear upon mouse movement. However, I am facing an ...

Ionic App experiencing issues with ngCordovaOauth plugin

I've been spending a lot of time trying to get the ngCordovaOauth plugin to function properly, but I keep encountering the same issue "Could not find InAppBrowser plugin." I have already installed the In-app-browser plugin and am utilizing ng-cordova ...

How can I extract text within a specific HTML tag using Selenium?

On my second day of learning Selenium, I am looking to extract text from within specific HTML tags. Here is a sample of the HTML code: <div id="media-buttons" class="hide-if-no-js"/> <textarea id="DescpRaw" class="ckeditor" name=" ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

What steps should be taken to trigger an API call once 3 characters have been entered into a field

In my current project, I am dealing with a parent and child component setup. The child component includes an input field that will emit the user-entered value to the parent component using the following syntax: <parent-component (sendInputValue)="g ...

Manipulating Response headers in an $http ajax request using AngularJS

Currently, I am working on processing the response headers but I'm a bit uncertain about how to retrieve them. Below is the code snippet where I made an attempt to read the headers, however I commented out a few lines and added some notes regarding my ...

Establishing a deadline for Firestore's Node.js library

When using the Firestore Node.js library, I often find that some operations, like fetching a document, can take longer than expected, sometimes even several minutes. I am looking to set a timeout or deadline of around 20-30 seconds for these operations. ...

ways to assign the total of string array elements to the $scope variable

I've been working on binding the total sum of selected checkboxes within a table. I'm almost there, but something isn't quite right. The image above shows 2 checkboxes selected. https://i.sstatic.net/70af2.jpg The code snippet below showcas ...

Sending Array Data from Controller to Factory in AngularJS

Can array data be transmitted from a controller to a factory, extracted from the factory, and then inserted into a database using Slim framework? Array[{}] CONTROLLER -> FACTORY -> SLIM PHP FRAMEWORK -> DATABASE I am new to AngularJS. Could you ...

My code gets disrupted when I use classes instead of IDs

My HTML code works fine when I use IDs and select them in my javascript with getElementByID. However, if I switch to using classes instead of IDs, my code stops working. I want to switch to using classes because I am collaborating on a project with someon ...

Increase the border at the bottom while hovering with React.js and the Material UI library

Can someone help me achieve a hover effect similar to the one in this question on Stack Overflow: Hover effect : expand bottom border I am attempting to create the same effect in React using makeStyles of Material UI. Here is my current code: const useSty ...

Error Occurs: 'PRM_MissingPanel' randomly in Ajax Update Panel

When using the Ajax Update Panel in Visual Studio to handle post backs for my search function, I encounter an issue. After generating a gridview with the results (i.e., searching for a member), whenever I update to the newest version from TFS, an error is ...

What is the best method for converting a string picture URL into an image and showcasing it in an image tag?

I have a URL for an image that looks like this: C:\inetpub\MaujApp\OMSAPI\ManualReceivingImages\WhatsApp Image 2021-03-24 at 12.07.41 PM.jpeg My goal is to convert the original image and display it to the user using jQuery. I woul ...

How can I set up automatic language selection for Google Translate's menu indexing feature?

My goal is to implement an automatic page translation feature using Google Translate's Library. I have been following the instructions provided in this link: The issue lies in the code snippet below, where the select menu creation works fine, but acc ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...