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

Issue with authentication when accessing Google Video API

I'm attempting to utilize the Google API provided: I have downloaded the Sample Project and followed these steps: 1) Navigate to the Project Folder named API Video 2) Run npm install 3) Set GCLOUD_PROJECT = neorisvideo 4) Download Json from the C ...

Having trouble establishing a connection to SQL Server with tedious in Node.js

Trying to connect to the SQL Server "SQL.SCHOOL.EDU\STUDENTSQLSERVER,4500" from my school has been a real challenge for me using tedious. I am currently working on setting up a connection between my express back end and react front end. For now, I am ...

Guide to setting up and launching a JavaScript/Vue GitHub repository on your local machine

I have a cloned app located here: cvss-v4-calculator that I want to run locally for debugging with VS Code or a similar tool. However, I'm encountering difficulties in setting it up. I've been attempting to run this as a web page using node.js, b ...

neither displayed on the webpage nor logged in the console

As a beginner in ReactJS, I am facing an issue where my Product component is not showing up when I check in the browser. Surprisingly, there are no errors in the console. Both my index.html and app.js files are located at the same level. To run the app, I ...

Pass for Achieving the Bokeh2 Effect

I'm attempting to transfer the Bokeh2 Depth of Field effect to an effect composer pass. Every time I try to run it, I encounter the following error: glDrawElements: Source and destination textures of the draw are the same. Below is the render functi ...

Tips for automating the activation of intents at specific scheduled times in Dialogflow

I'm attempting to automatically trigger intents in Dialogflow to obtain the user's contact details at a scheduled time. Is it possible to achieve this using JavaScript? If so, could you please provide the code? ...

AngularJS Dropdown in ASP.NET MVC 3

I want to create a DropDownList using @Html.DropDownList and connect it with AngularJS. Below is the code snippet: @Html.DropDownList("LessonID", (SelectList)ViewBag.LessonList, "choose one", new { ng_model = "LessonID" }) Here's an example of ...

Encountering an unexpected token error while attempting to incorporate JQuery into a React JS project

I am currently diving into the world of React.js and attempting to incorporate a side navigation bar on my homepage. However, I encountered an eslint error when trying to implement the sidebar using jQuery code. Below you will find the code snippet for the ...

What setting should I adjust in order to modify the color in question?

Looking to Customize Radar Chart Highlighted Line Colors I am currently working on a Radar Chart and I am trying to figure out which property needs to be edited in order to change the color of the highlighted lines. I have already attempted to modify the ...

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

Utilizing ng-model on a pair of inputs to achieve synchronized values

Is it possible to use ng-model on an input field that receives a value from another input field? I'm having issues with my code and I can't figure out why. Can ng-model be set to an input field using Angular values? Here's my code: ...

Showing data from a MySql database using an HTML table

I am currently working on a pop-up form that captures user data and stores it in a MySQL phpmyadmin table. My goal is to have this data displayed in an HTML table once the popup form is closed. After submitting the form, I am redirected back to the homepag ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

Utilizing JavaScript to handle the value from a selected form

My form is quite simple: <form id="signup"> <div class="form-group"> <input type="text" name="email" placeholder="Email" id="email" required> </div> <div class="form-group"> <input type= ...

Passing an anonymous function as a parameter to a function in ng-init is a common practice in AngularJS v1.4.8

Is it possible to save a call to an anonymous function using ng-init? For example: <div class="container-fluid" ng-app="AVF" ng-controller="ConfigController" ng-init="RegisterInitFunction(function() { $scope.GetData(); })" > In my controller: ...

Ways to eliminate empty values from an array in JavaScript

I need help deleting any null elements from my array [ [ null, [ [Array], [Array] ] ] ] I am looking to restructure it as [ [[Array],[Array]], [[Array],[Array]], [[Array],[Array]] ] If there are any undefined/null objects like : [ [[Array],[]], [[A ...

Retrieving a list of numbers separated by commas from an array

Currently, I'm retrieving data from a MYSQL database by executing the following SQL command: SELECT GROUP_CONCAT(MemberMemberId SEPARATOR ',') AS MemberMemberId FROM member_events WHERE event_date = "2000-01-01" AND Eve ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

Is it possible for the children of a Three.js scene to have matrix positions that differ from the children of those children?

I am facing an issue with my ferris wheel. The baskets on the wheel are not aligning correctly when the scene is rotated: https://i.sstatic.net/Ek1mT.png Everything functions as intended until the scene is rotated, causing the baskets to misalign with th ...

Exploring the intricacies of initializing a JavaScript function

I recently inherited a large JavaScript file from a previous developer, and I'm trying to decipher some of the key sections. Here is the complete code: $(function () { var homepage = (function () { // Main functionalities are defined he ...