What's the reason behind ng-click only functioning with a function and not an assignment within this specific directive?

I am currently working on creating a dynamic table using an array of objects that can be sorted by clicking the headers. I have a specific question regarding how the sorting feature is implemented.

let myDirectiveTemplate = `
<table class="directiveTable">
  <thead>
    <th ng-repeat="(key,val) in tableObjectArray[0] track by $index">
      <a href="" ng-click="changeCriteria(key)">
        {{key}}
      </a>
    </th>
  </thead>
  <tbody>
    <tr ng-repeat="object in tableObjectArray | orderBy:criteria track by $index">
      <td ng-repeat="prop in object track by $index">
        {{prop}}
      </td>
    </tr>
  </tbody>
</table>
`

let app2 = angular.module('myDirectiveModule', []);

let myDirective = () => {
  return {
    restrict: 'E',
    scope: {
      tableObjectArray: '=objects',
    },
    controller: myDirectiveController,
    template: myDirectiveTemplate,
  }
};

let myDirectiveController = ($scope) => {
$scope.changeCriteria = criteria => {
  $scope.criteria = criteria;
}
};

app2.directive('myDirective', myDirective);
app2.controller('myDirectiveController', myDirectiveController);

The current implementation works as expected. However, when I try to change the ng-click attribute in the template to

ng-click="criteria = key"

it doesn't seem to have any effect. Even when I try to display the variable using double curly braces, it does not update upon clicking. I have used variable assignment in an ng-click before without issues; so I'm curious why this behavior is occurring?

Answer №1

When using ng-repeat, a child scope is created for each item, which means that any changes made to a primitive will only affect that specific child scope. This is because there is no inheritance with primitives, so the parent scope in the controller remains unchanged.

If you instead use an object declared in the controller, or utilize the ControllerAs alias, the inheritance will work correctly.

$scope.myModel = {criteria: 'defaultValue'}

ng-click="myModel.criteria = key"
<tr ng-repeat="object in tableObjectArray | orderBy:myModel.criteria track by $index">

In terms of debugging and testing, it is generally recommended to use a function.

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

The image is failing to animate according to the PNG sequence function

Enhanced Functionality: Upon clicking the "Tap Here" image button, a function called "GameStart()" is triggered. This function ensures that the main image "Star" descends down the page from the top through an animated sequence using png logic. The propose ...

Unexpected results from the match() function

Attempting to utilize the RegExp feature in Javascript (specifically with the match function) to locate instances of a sentence and a specific word within that sentence embedded in the HTML body. Provided is some pseudo-code for reference: <!DOCTYPE ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

Learn to save Canvas graphics as an image file with the powerful combination of fabric.js and React

I am currently utilizing fabric.js in a React application. I encountered an issue while attempting to export the entire canvas as an image, outlined below: The canvas resets after clicking the export button. When zoomed or panned, I am unable to export co ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

Utilize JSON to create a dictionary populated with objects following a complex grouping operation

I am faced with a JSON query that contains the Date, Value, Country, and Number fields. My goal is to create two separate JSON dictionaries based on unique dates (there will be two of them). The desired output can be seen in the code snippet below along wi ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...

Showing scheduled activities from a database on an AngularJS mwl calendar

How can I modify my code to display events from a database on an mwl calendar based on the saved date rather than showing all events for today only? I want to show events based on the notifyDate field in the database. Can someone help me with this? html ...

What could be the reason why readyState is not equal to 4?

I've been trying to figure out how to use Ajax to fetch data from a database, but I'm encountering some issues... The problem arises when I submit the query and nothing appears on the screen... I understand that this issue is related to the read ...

Utilize text wrapping to ensure a fixed maximum height for content display

I am in need of a div that contains text spanning multiple lines, with both a fixed width and a maximum height. Currently, I have applied the CSS property overflow: hidden;. However, my issue arises when the last line of text exceeds the maximum height of ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

Implementing a click event listener on an iframe that has been dynamically generated within another iframe

Below is the code I used to attach a click event to an iframe: $("#myframe").load(function() { $(this.contentWindow.document).on('click', function() { alert("It's working properly"); }); }) Everything seems to be working co ...

Error message: Unable to split path as a function when utilizing React hook forms in conjunction with Material UI

Check out this code snippet: <TextField name="name" required className='my-2 mx-auto' label="Full Name" variant="standard" style={{ "width": "60%" }} value={name} onChange={(event) => { set ...

Vue.js is displaying an error message stating that the data property is

I am struggling to access my data property within my Vue.js component. It seems like I might be overlooking something obvious. Below is a condensed version of my code. The file StoreFilter.vue serves as a wrapper for the library matfish2/vue-tables-2. &l ...

Creating an array of options for a jQuery plugin by parsing and populating

I am currently in the process of developing my very first jQuery plugin. The main function of this plugin involves taking JSON data and loading it into a table. Although most of the logic has been implemented successfully, I am facing challenges when it co ...

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

Attempting to modify the array content using useState, but unfortunately, it is not functioning as expected

Starting out with react.js and trying to update an array's content using useState upon clicking a send-button, but it's not working as expected. Struggling with adding date and number in the row. Check image here Here's what I'm aiming ...

How to toggle the display of a div by its id using index in Javascript

Currently, I am encountering a problem with toggling the div containers. When I click on the video button, I want the other divs to close if they are already open. However, due to the toggling mechanism, if a div is closed and I click on the corresponding ...

Angular material table featuring custom row design

My team is working with a large table that is sorted by date, and we are looking to add some guidance rows to help users navigate through the data more easily. The desired structure of the table is as follows: |_Header1_|_Header2_| | 25/11/2018 | ...