Retrieving a value attribute from the isolated controller of a directive

I have a directive that reads and writes attributes, but I'm having trouble getting it to work as expected. The issue seems to be with the controller inside main-directive.js, which is empty, while the actual action is happening in the isolated directive's controller.

You can view a live demo on Plunker: http://embed.plnkr.co/IkKPLahPc9yqeHWEQUG3/

In the main-directive.js file:

var app = angular.module('testapp.directive.main', ['main']);

app.directive('myCustomer', function() {

  var controller = ['$scope', function($scope) {

    $scope.dan = { 'name': 'Chad', 'nationality': 'China' };
    // I want the scope.dan object to be read from here.

  }];

  var template = 'Getting attribute value of =getInfo... {{getInfo.name}} from {{getInfo.nationality}}';

  return {
    restrict: 'E',
    controller: controller,
    scope: {
      getInfo: "=info"
    },
    template: template
  };
});

app.controller('ctrl', function($scope) {
  // adding the $scope.dan object here will work
  // but I don't want it here.
});

And here's the template for it:

'mainview@': {
    controller: 'MainCtrl as mainCtrl',
    template: '<div ng-controller="ctrl"><my-customer info="dan"></my-customer></div>'
}

How can I ensure that the directive reads objects from its isolated controller rather than the 'ctrl' controller?

Thank you.

Answer №1

Check out this insightful post demonstrating how directives and controllers interact within the same $scope.

Behavior of controller inside directives

It seems like you are curious about the custom attributes assigned to your customized HTML tag. I have revised your directive and controller, showcasing the info attribute that caught your attention.

var app = angular.module('testapp.directive.main', ['main'])
  .directive('myCustomer', function() {

  var template = 'Getting attribute value of =getInfo... {{getInfo.name}} from {{getInfo.nationality}}';

  return {
    restrict: 'E',
    controller: 'ctrl',
    scope: {
      getInfo: "=info"
    },
    template: template
  };
})
.controller('ctrl',['$scope', '$attrs', function($scope, $attrs) {
  $scope.dan = { 'name': 'Chad', 'nationality': 'China' };
  console.log($attrs.info);
}])

I hope this clears things up for you.

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

JavaScript functions with similar parent names

Explain a function that has identical functionality to its parent parent.document.getElementById(source).innerHTML should be the same as other-function-name.document.getElementById(source).innerHTML ...

Encountering an Error while Setting Up NextJS on Vercel

Hello, I'm a newcomer to the world of web development. My current goal is to deploy my first NextJS app on Vercel, but I keep encountering an error. Error: SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...

What steps should I follow to integrate aws-appsync into my AngularJS project?

I'm diving into a project with AngularJS, utilizing bower as the package manager and gulp to inject dependencies into the index.html file. These tools are fairly new to me. Now, I want to incorporate AWS AppSync, but unfortunately it's not avail ...

Is it possible to utilize a single template and dynamically fill it with content as needed?

Is there a method to utilize a single template and dynamically insert content into it? http://jsfiddle.net/cmckeachie/mtV62/light/ var routingExample = angular.module('FunnyAnt.Examples.Routing', []); routingExample.controller('HomeControl ...

Is there a way to serve server-side rendered content exclusively to search engine crawlers like Google Bot, without SSR for regular users in Next.js?

With a staggering number of users visiting the site every day, we are making strides to enhance our visibility on Google by implementing SSR (which may sound unbelievable) and achieving a richer preview when content is shared on messaging platforms. As th ...

What is the best way to use AJAX to load a PHP file as a part

I'm exploring different methods for making an AJAX call with an included file. Let's create a simple working example. Initially, I have my main index.php file which contains the following content. In this file, I aim to access all the data retur ...

Creating a script that automatically launches the terminal and executes specific commands

Can anyone help me with creating a file that, when clicked on, opens a command prompt and executes the following commands? cd desktop\discordBOT node . Many thanks in advance! ...

Loop through a variable class name in JavaScript

When working with Javascript, I have a series of elements with identical divs: (....loop, where "count" is a unique number for each column) <other divs> <div class="pie"></div> </div> My goal is to be able to rotate each individ ...

What is the best way to convert a dynamic HTML table with input fields into an Excel spreadsheet?

I have developed a JavaScript function to convert an HTML table into an Excel sheet. However, I am facing an issue where some fields in the table are enclosed in input tags instead of td tags, causing them to not appear in the Excel sheet. function expo ...

What is the process of disabling console log in a Vue template?

Origins of the $log variable: Vue.prototype.$log = console.log Restricted Areas: <template> <!-- Restricted Area 1 --> <div @click="$log"> <!-- Restricted Area 2 --> {{ $log }} <!-- Restricted Area 3 -- ...

Can anyone recommend any offline editors for HTML, CSS, and JavaScript similar to JSFiddle, jsbin, or codepen?

Is there an alternative to JSFiddle.net that allows users to experiment with Javascript, HTML, and CSS offline in a similar way? ...

Harness the power of a NUXT component on a different website

Currently, I have a fully functional NUXT application that consists of numerous pages and components operating in `universal` mode. My challenge now is to render one of these components on a separate static HTML website. Exporting a component from a stand ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Invoking Angular component method using vanilla JavaScript

For my web application, I am utilizing Angular and require Bluetooth functionality on a specific page. I am implementing loginov-rocks/bluetooth-terminal (https://github.com/loginov-rocks/bluetooth-terminal) for establishing the Bluetooth connection, which ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

The hyperlink tag within the overlay div is unresponsive

I'm facing an issue with my overlay div (rb-overlay) that pops up when users click on a page option. The overlay takes up the entire page and includes a close button in the top right corner. However, I've noticed that the link at the end of the t ...

Can an unresolved promise lead to memory leaks?

I have a Promise. Initially, I created it to potentially cancel an AJAX request. However, as it turns out, the cancellation was not needed and the AJAX request completed successfully without resolving the Promise. A simplified code snippet: var defer = $ ...

What is the best way to utilize the Material UI theme provider in a React application that includes a mix of class components and functional components?

I have been working on a React app that utilizes class components, but I have been transitioning to using functional components instead. I have replaced some class components with functional ones in the application. However, I have encountered an issue whe ...

Exploring Angular Factory: Creating the getAll method for accessing RESTful APIs

In my Angular.JS factory, I am retrieving data from a REST Api. The REST Api endpoint is "/api/getSsls/1", where 1 represents the page number. The API response is in JSON format and contains the first ten items along with total pages/items information. I ...