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

What is the best way to switch between components in vue.js?

I have created a Dashboard.vue component consisting of two child components: DisplayBooks.vue and sortBooksLowtoHigh.vue. Initially, the sortBooksLowToHigh component is hidden while the displayBooks component is visible by default. The requirement is that ...

Learn how to efficiently send multiple image files to the server by utilizing Formidable and React JS

I am encountering an issue while attempting to upload five images to the server. The code file is provided below, and any assistance would be greatly appreciated. In this scenario, I am inputting image files and storing them in an array, but Formidable in ...

How can I transform a Firestore collection into an array?

I'm struggling with converting the data retrieved from Firestore into an array that can be used for a chart.js graph. Retrieving Data from Firestore fetchData(){ //Get data this.updatesCollection = this.afs.collection(pathStats); this. ...

Is it possible to use HTML alone in Bootstrap 5 to link a button to display a toast notification?

I'm working on a Bootstrap page that includes a button and a toast element sourced from the Bootstrap documentation. The documentation states that I need to initialize the toast in JavaScript during page load. My goal is to have the toast appear when ...

`local data erasing in Ionic app on both iOS and Android devices`

I am in the process of developing a mobile application with a backend server built on Rails. The main concept is that upon successful user sign-in, the server sends back a unique token along with their user_id. These two pieces of information are stored in ...

Dealing with undefined or null values when using ReactJS with Formik

Issue Resolved: It seems that Formik requires InitialValues to be passed even if they are not necessary. I'm currently working on a formik form in React, but every time I click the submit button, I encounter an error message stating "TypeError: Canno ...

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

Transferring String data between Java and JavaScript using Webview in both directions

I'm currently developing an application that allows two users to communicate via a webview. My goal is to transfer a String variable from JavaScript to Java in order to store it in my SQLite database, and also be able to do the reverse operation as we ...

Updating AngularJS views based on window resizing

I've been working on an Angularjs application and everything is running smoothly, but I'm facing challenges when it comes to implementing a mobile version of the site. Simply using responsive styles won't cut it; I need to use different view ...

Struggling to integrate an audio player specifically for mp3 files and feeling quite perplexed by the process

I'm struggling with implementing an audio player for a file sharing platform, specifically only for .mp3 files. I have successfully implemented a function for images (.jpeg and others), but I am unsure how to do the same for mp3 files. function is_au ...

What is the most effective way to show the current date on a webpage: utilizing JavaScript or PHP?

Looking to show the current date and time on a webpage. There are two potential methods to achieve this: (1) Using PHP, for example: <?php echo date('Y-m-d H:i:s');?> (2) ... or JavaScript, like so: <div> <script>document.wri ...

Understanding how to effectively conduct unit tests on the 'resolve' property within an Angular-UI Bootstrap Modal component is essential for ensuring the functionality and

I'm currently working on building a unit test that verifies the correct variable is being passed to the resolve property within the ui.bootstrap.modal from Angular-UI Bootstrap components. Here's my progress so far: // Controller angular.module( ...

What are some methods to activate a scope watch within a directive?

I'm attempting to activate my directive code using a scopewatcher: var gMaps = function($timeout, $q, GeoCoder, mockdataService) { return { restrict: 'EA', template: '<div class="gmaps"></div>', ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...

Having trouble viewing the page of a new package you published on the NPM Website?

Today, I officially released an NPM package called jhp-serve. It can be easily installed using npm install or run with npx. You can even find it in the search results here: https://www.npmjs.com/search?q=jhp. However, when attempting to view its page by cl ...

Why isn't offsetTop working for a div within a table in HTML and Javascript?

When using the offsetTop property to get the absolute position of an object, it works fine when the objects are outside of tables. However, if the object is inside a table, it always returns 1. Why does this happen and how can it be avoided? To see an exa ...

What is the reason for the checkboxes in vuejs not being rendered with the checked attribute set

When working on an edit form, I encountered a situation where I had multiple options to choose from. These options were fetched via ajax using axios and assigned to the variable permisos in the component. Later, these options are rendered through a v-for l ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...