Angularjs Directive content not bound to isolated scope

I'm currently exploring directives and my goal is to bind a value to my grandchild component, then update the parent element. However, I've encountered an issue as this code does not propagate up to the root.

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

myApp.controller('root', function ($scope) {
  vm = this;
vm.value = 'Joe Doe';
});

myApp.directive('child', function () {
return {
  restrict: 'A',
    scope: {
      paramOne: '=paramOne'
    },
    link: function (scope, elm, attrs) {
      console.log('Child value: ', scope.paramOne);
    }
  }
});

myApp.directive('grandchild', function () {
return {
  restrict: 'A',
    scope: {
      paramTwo: '=paramTwo'
    },
    link: function (scope, elm, attrs) {
      console.log('Grandchild value: ', scope.paramTwo);
    }
  }
});
<script src="//unpkg.com/angular/angular.js"></script>

<div ng-app="myApp" ng-controller="root as vm">
  Field Value: <strong>{{vm.value}}</strong>
  <hr>
  <div child param-one="vm.value">
    Child param value: {{paramOne}}    
    <div grandchild param-two="paramOne">
      Granchild param value: {{paramTwo}} <br>
      <input type="text" ng-model="paramTwo" >
    </div>
  </div>
</div>

I have conducted some research but have not found a solution for this particular scenario. Any help provided would be greatly appreciated :)

Answer №1

To make the directives transclude the contents and attach them to the element in the linking function, you can use the following code:

    transclude: true,
    link: function (scope, elem, attrs, ctrl, transcludeFn) {
      transcludeFn(scope, function(clone) {
        elem.append(clone);
      });

Click here for a DEMO

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

myApp.controller('root', function ($scope) {
    vm = this;
    vm.value = 'John Doe';
});

myApp.directive('child', function () {
return {
    restrict: 'A',
    scope: {
      paramOne: '=paramOne'
    },
    transclude: true,
    link: function (scope, elem, attrs, ctrl, transcludeFn) {
      transcludeFn(scope, function(clone) {
        elem.append(clone);
      });

      console.log('Child value: ', scope.paramOne);
    }
  }
});

myApp.directive('grandchild', function () {
return {
    restrict: 'A',
    scope: {
      paramTwo: '=paramTwo'
    },
    transclude: true,
    link: function (scope, elem, attrs, ctrl, transcludeFn) {
      transcludeFn(scope, function(clone) {
        elem.append(clone);
      });

      console.log('Grandchild value: ', scope.paramTwo);
    }
  }
});
<script src="//unpkg.com/angular/angular.js"></script>

<div ng-app="myApp" ng-controller="root as vm">
  Field Value: <strong>{{vm.value}}</strong>
  <hr>
  <div child param-one="vm.value">
    Child param value: {{paramOne}}    
    <div grandchild param-two="paramOne">
      Granchild param value: {{paramTwo}} <br>
      <input type="text" ng-model="paramTwo" >
    </div>
  </div>
</div>

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

Having trouble with getting angular $http to function properly

I'm currently working on setting up an angularjs login screen. The way it's supposed to work is that the angular app will send the login details via an http get method to a java servlet and then wait for a json response indicating success or fail ...

The issue lies in the constructor not properly updating the property when referencing "this

Apologies for the confusion with the question title, I am still new to using constructors in JavaScript and struggling with how to properly phrase it. Here is the issue I am facing: I am implementing a Builder pattern (using a constructor) to create an ob ...

Issue with Cordova file plugin's inability to write to file

Currently tackling an issue with the Cordova file plugin (version 3.4.1) on Android. Despite combing through documentation, including the HTML5 file storage API and numerous StackOverflow posts (most of which suggest installing the plugin first - already d ...

Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality. loginController.js: var loginAdmin=angular.module('Channabasavashwara'); loginAdmin.controller('log ...

transferring attributes from a component iterated over to a component it renders

Admitting my lack of expertise, I am seeking assistance with the implementation of the following code. This is my "posts" component responsible for making an API call to fetch all post data: import React from 'react' import Post from '../pos ...

Programmatically installing Npm is ineffective

I am currently attempting to interact with the npm api programmatically, as illustrated in the code snippet below: var npm = require("npm"); npm.load(npm.config, function (err) { npm.commands.install(["express"], function(err, done) { console ...

Encountering a 'JSON parsing error' while transmitting data from Ajax to Django REST Framework

I've been encountering an issue while trying to send a JSON to my REST API built with Django Rest Framework. Every time I make this request, I receive an error message, regardless of the view I'm accessing. I suspect the problem lies in the AJAX ...

The event was triggered, however, some sections of the code did not run

I am currently working on a project called lan-info on GitHub. Here is the code snippet that I am using: let arpSweepCommand = './arpSweep.sh'; app.get('/arp', (req, res) => { console.log('we have a working signal!'); ...

React - a search feature for array filtering

Lately, I've been delving into the intricacies of implementing a live search input that interacts with an array to create a file tree. Here is where you can find all the code: https://codesandbox.io/s/815p3k3vkj Although the solution seemed straightf ...

Obtaining the chosen options from a dropdown menu

I am facing an issue with retrieving values from dropdown menus on a webpage that are used to filter a list. Despite trying various methods, I am not getting any values returned in my function. Here is what I have attempted: - var browserVal= document.ge ...

Why is my Next.js scroll event not triggering when scrolling?

useEffect(() => { document.addEventListener("scroll", ()=> { console.log('.................gotcha'); }); },[]); I am trying to trigger an event when the user scr ...

What are the steps to customize the appearance of a folder in the web browser?

Is it possible to customize the presentation of folder contents dragged into Chrome using CSS, HTML, JavaScript, or other methods? I've heard about the HTML5 file API but not sure if that's applicable in this scenario. I think it would be intere ...

How can I use a string argument in JavaScript to sort an array of objects by that specific value?

Currently, I am implementing React and facing a challenge with creating a reusable sorting component. This component is meant to sort an array of objects based on a specific property field. For instance, imagine having an array of objects with properties a ...

Is it possible to define valid values for named groups using regex in Angular's $routeProvider?

My dilemma involves loading a controller only if the first path argument corresponds to a valid "sorting" value. For example: /date /name Otherwise, it should display my error page. My routeProvider setup is as follows: $routeProvider. when(&ap ...

Tips for activating animated text upon hovering over a text or image:

My brand name is: Code The navigation bar displays as follows: Code Home | Service | Product | Contact I would like to change the appearance of my brand name from Code to { Code } when users hover over it. Additionally, I wish to style the brackets { ...

Error message displaying NaN and issues with setting class using color function in console log

The console log is displaying NaN for any variable I input. Additionally, the color function is not correctly changing classes, likely due to the number issue. I still need to address local storage, but my main focus is on getting the variable to display ...

How to convert a 4-bit byte array into an integer using JavaScript

Utilizing web sockets, I transmit a 4-bit byte array to my JavaScript library. This byte array signifies a number that I want to retrieve back, all within JavaScript. Examples abound for reading a byte array into a string, but finding examples for the reve ...

When I execute the `npm run build` command on my React website, I am facing an issue where only the Navbar and Footer components are

I'm facing an issue on my React website where the home component is not displaying on the home page after running the `npm run build` command. When I access the built HTML file, only the Navbar and Footer components are visible. However, when I click ...

Load Express JS router middleware conditionally based on certain conditions

In my Express JS code, I have implemented a middleware that defines specific end-points on a router for user login and logout. However, I am now integrating a new authentication method where the auth token is received from a different service. In this case ...

Utilizing Visual Studio: Implementing jsmin in post-build actions

After attempting to add jsmin.exe as a post-build event in my VS 2010 project, I encountered an "error code 9009" when building the project. I tested this in the command prompt and found that it works if I navigate to the folder and run: jsmin < debug ...