Example: Utilizing data transfer from model to directive

I have a question regarding a specific part in an example from Thinkster. I believe my confusion is due to my limited understanding of JavaScript and AngularJS fundamentals. I've been teaching myself since December, starting with the basics of JavaScript and now diving into Angular. If you could explain it to me as if I were 5 years old, I would greatly appreciate it! Check out the Thinkster Page here

App.js

app.controller("ChoreCtrl", function($scope){
  $scope.logChore = function(chore){
    alert(chore + " is done!");
  };
});

app.directive("kid", function() {
   return {
    restrict: "E",
    scope: {
    done: "&"
   },
    template: '<input type="text" ng-model="chore">' +
    //I'm slightly confused about this particular section

      '{{chore}}' +
      '<div class="button" ng-click="done({chore: chore})">I\'m done</div>'
  };
});

HTML

<div ng-app="choreApp">
     <div ng-controller="ChoreCtrl">
        <kid done="logChore(chore)"></kid>
     </div>
</div>

How does {chore:chore} actually work? According to Thinkster:

The {chore:chore} syntax links the chore value from the input model to be passed to the logChore function when we use 'done="logChore(chore)"' (in the kid directive)

Here are my thoughts:

  1. Clicking invokes "done", which further triggers "logChore(chore)" based on the HTML attribute
  2. I assume that "{chore:chore}" in App.js is being passed to logChore, so it's like calling logChore(chore:chore)?

Why can't we simply use ng-click=(done(chore))? What is exactly happening with {chore:chore}? It might be obvious that I am pretty lost in all this haha.

Thank you very much for your help!

Answer №1

The reason for this behavior is due to the use of the & operator, which you can understand more deeply by referring to this link: https://docs.angularjs.org/api/ng/service/$compile#-scope-

Here's what it means:

The & or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name.

In simple terms, this allows us to access the `chore` property of the parent scope, as without it we would be limited to the directive's isolate scope where `chore` property does not exist.

You can also check out further explanation at:

To enhance clarity, I've made some modifications to the code. Now, we have property names like `innerChore`, `outerChore`, and `param` to prevent any naming conflicts:

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

app.controller("ChoreCtrl", function($scope){
  $scope.logChore = function(param){
    alert(param + " is done!");
  };
});

app.directive("kid", function() {
  return {
    restrict: "E",
    scope: {
        done: "&"
      },
    template: '<input type="text" ng-model="innerChore">' +
      '{{innerChore}}' +
      '<div class="button" ng-click="done({outerChore: innerChore})">I\'m done</div>'
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<div ng-app="choreApp">
  <div ng-controller="ChoreCtrl">
    <kid done="logChore(outerChore)"></kid>
  </div>
</div>

Pay attention to the relationship shown in {outerChore: innerChore}.

Answer №2

Consider the meaning behind the done attribute expression: logErrand(errand). This code is evaluated within the context of the $scope for the ErrandCtrl (meaning that all variables and functions must be part of that specific scope). So, let's examine which variables and functions are being referenced here: logErrand() and errand. It's clear that logErrand() is a defined function property on the $scope, but what about errand? It doesn't exist on the $scope object at all!

Now, when you invoke .done() within the directive's link() function, you provide a locals map that specifies values for variables, overriding any existing ones on the $scope. In this scenario, using {errand: errand} means "utilize the errand object from the directive's isolated scope as the value for the errand variable in the specified expression for the done attribute." Suddenly, we have clarity on what errand represents in the logErrand(errand) expression.

Does this explanation offer more insight?

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

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

Tips for accessing hidden field values in a second jsp page

I have a webpage called page1.jsp where I am including hidden fields. Here is the code snippet: <form action = "page2.jsp" method = "post" id = "hiddenValuesForm"> <input type = "hidden" name = "userData" value="" id = "useDataID"> <input t ...

The eel feature results in no output

During my Python program development using the Eel module, I encountered an issue. The problem is that the eel.getImgSrc(path) function returns null when trying to retrieve image's byte data. Take a look at this example: -----web/main.js------ async ...

Steps for selectively extracting objects from an array containing nested objectsNeed a way to isolate specific objects

Currently, I am working on a project in JavaScript and have created an array called folders that holds multiple objects: folders = [folder1, folder2, folder3...] Each object within the array has various properties, one of which is docs that is an array o ...

How to Access a div from another website using jQuery

I have a question. How can I call a div from another website using JavaScript? Here is the page: Now, I want to call the <div id="testa"> in another page. The other page is called Otherpage.html: jQuery(function($){ $(&ap ...

What could be causing the target to malfunction in this situation?

Initially, I create an index page with frames named after popular websites such as NASA, Google, YouTube, etc. Then, on the search page, <input id="main_category_lan1" value="test" /> <a href="javascript:void(0)" onmouseover=" window.open ...

I designed my higher-order component to allow for dual invocations. How can I integrate Redux within this framework?

I have implemented my higher-order component (HOC) in such a way that it can be invoked twice, emphasizing the concept of "functional programming". However, I am facing challenges in connecting Redux to access state and certain functions. I would greatly ...

Processing the retrieved object from Dropbox API using Node.js and Express

I've been attempting to carry out a simple task like uploading a file to Dropbox. The file uploads successfully, but I'm in need of the response that contains details such as the file name, size, and path. I understand that I'm getting lost ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

Using Angular's ui-router to pass and access parameters in your

I am currently facing an issue while using Angular with ui-router. Everything is working smoothly except for one particular scenario. I have designed a directive element that serves as the header of the page. This element consists of a menu with 4 links. T ...

Ways to clear the time attribute from an ISO DateTime in date format

How can I remove the time attribute from a date in the format 2016-05-24T05:07:57.756Z and set it to something like 2016-05-25T00:00:00.000Z? Any assistance would be greatly appreciated. ...

The URL dynamically updates as the Angular application loads on GitHub Pages

Encountering an unusual issue when trying to access my angular website on GitHub pages. The URL unexpectedly changes upon opening the page. Please check it out at this link: The original expected URL should be However, as the page loads, the URL gets alt ...

When a click event triggers, use the .get() method in jQuery to retrieve the content of a page and then update

I am currently facing an issue with a div class="contentBlock", which is acting as the container for updating content. <div class="contentBlock"></div> Unfortunately, the script I have written does not seem to be working properly :c $(docume ...

Displaying error message on a MEAN stack web application

I'm pretty new to the MEAN stack and I must say, I'm learning a ton. Currently, my challenge is to display an error message on my page when a user is not authorized to access the website. On the page, there's a button that redirects you to t ...

What is the comparable javascript code for the <script src="something1.json"></script> tag?

Within my HTML code, I currently have the following line to read a JSON file: <script src="something1.json"></script> Inside this JSON file, there is a structure like so: var varName = { .... } This method of definition naturally sets up ...

Can you verify the standard behavior when importing index.js using create-react-app?

I'm trying to wrap my head around why, when using create react app, if a folder contains an index.js file and you want to import it, you only need to specify the folder name. I've been wondering where this default behavior is configured to autom ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

Updating local variable value in Node.js from an event listener

How can I modify a local variable within an event handler, listener, or function? export async function mis() { let result; // <--------- LOCAL VARIABLE I WANT TO MODIFY (currently undefined) const m = await spawn(`/cmd`); m.stdout.on('data ...

In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage. I am currently developing an Angular7 application. In one of my ...