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

Removing multiple data rows in JSP using AJAX by selecting check boxes

I have a requirement where I need to store a list of objects (each with a unique id) as a session parameter. These objects are then displayed in a table in a JSP using JSTL. <c:forEach var="list" items="${PlayerList}"> <tr> <td> ...

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...

Detecting a click event within a hidden div located behind another visible div

I am facing an issue with triggering ng-click in a div that is covered by another div. The current scenario I have is as follows: https://i.sstatic.net/SfM5y.jpg Basically, I need to activate ng-click on the yellow circle when it is clicked. However, the ...

"Error alert: The specified property 'Iscontains' cannot be read because it is undefined" appears in the script for this video

I am currently utilizing AJAX to interact with my backend code. I retrieve URLs from the database and then render them onto the DOM, displaying videos accordingly. However, I am encountering an issue where Uncaught TypeError: Cannot read property ' ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

Using CasperJS, learn how to effectively utilize the jQuery find() function

I'm looking to implement something similar to Cabybara within a function in CasperJS. My goal is to select parent divs and extract text from their child elements. Here's an example of what I want: $('div.education').find('h4&apos ...

The property 'get' cannot be accessed because the axios module of vue__WEBPACK_IMPORTED_MODULE_0__ is undefined

Having some trouble with Vue and Axios - encountering the following error message: [Vue warn]: Error in created hook: "TypeError: can't access property "get", vue__WEBPACK_IMPORTED_MODULE_0__.default.axios is undefined" Here's the code snippet: ...

Utilizing AngularJS to create a cascading drop-down menu

I am attempting to create a cascading drop-down menu where the second drop-down will display options related to the item selected in the first drop-down box. However, even after trying some sample code, the second drop-down remains empty. Here is the HTML ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

Using Angular's ng-click to navigate to a new page and sending parameters:

Upon clicking the edit button, a new page will be opened and a REST call will be made to populate the page with the parameters passed in. ...

The Foolish Mistake: Undetermined Dollar Sign

Can someone please help me with this issue? I've searched everywhere but I can't seem to fix the "Uncaught ReferenceError: $ is not defined" error. I have rearranged my script, tried putting it at the bottom, but nothing seems to work. Any sugges ...

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

Using client-side navigation within an integrated Shopify application

Seeking assistance in implementing client-side routing with react-router within a Shopify app that is embedded. Following the guidelines provided by Shopify on this page, but unsure about what needs to be included in a ./Routes file. Attempted to find rela ...

Ways to break apart a string of text without a regular pattern

Here is the data I am working with: Huawei Y7P Art-L28 (4/64gb) (AAAAAAAAAAAAAA) EXP:02/19/2020 Huawei Y9 prime 2019 (BBBBBBBBBBBBBBB) EXP:07/17/2019 Oppo A31 4gb/128gb (CCCCCCCCCCCCCCC) Vivo Y15 5000mah 4GB/64GB (1901) (DDDDDDDDDDDDDDD) EXP:06/14/2019 I ...

What are some ways to include additional data besides the new value in a change event for an input field?

Currently, I am using VueJS to dynamically generate a form based on a JSON schema and then attempting to save the data into my Vuex state. Here is an overview of the code I have written so far (simplified): <div v-for="field in schema" :key=& ...

Tips for stacking objects vertically in mobile or tablet view using HTML and CSS

I have been diligently working on a project using a fiddle, and everything appears to be running smoothly in desktop view. The functionality is such that upon clicking any two product items (with one remaining selected by default), a detailed description ...

Transform all Date fields in the Array to a standardized date format

I have an array with various fields, including a field called dateofbirth. I need to remove the time and change the format to MM-DD-YYYY. var records = [ { "recordno":"000001", "firstname":"Bo", "middlename":"G", "lastn ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...