Insert a fresh directive within an ng-repeat loop

I currently have an array of data that is being shown using a directive within an ng-repeat. Whenever the user clicks on a button, a new object is added to this array which requires a new instance of the directive to be executed. Here is my current HTML setup:

<ul>
  <li ng-repeat="c in commissions" commission="c.commission" index="{{$index}}"></li>
</ul>

Whenever the user clicks the "add" button, the following CoffeeScript function is triggered:

$scope.newCommission = function() {
  var commission;
  commission = {
    new_commission: true
  };
  return $scope.commissions.push(commission);
};

This is my current directive:

var Commission;

Commission = function() {
  return {
    restrict: 'A',
    replace: true,
    templateUrl: '/assets/template/commission/list.html',
    controller: 'ProductEditCtrl',
    scope: {
      commission: '=',
      index: '@'
    },
    link: function(scope, el, attrs, ctrl) {
      var commission;
      commission = scope.commission;
      commission.index = scope.index;
      scope.editable = false;
      scope.changeType = function(type) {
        return commission.type = type;
      };
      scope.removeCommission = function() {
        return ctrl.deleteCommission(commission.index, commission.id);
      };
      scope.saveCommission = function() {
        var obj;
        obj = {
          seller_id: commission.seller.id,
          type: commission.type,
          value: commission.value
        };
        ctrl.changeCommission(commission.id, obj);
        return scope.editable = false;
      };
      return scope.turnEditable = function() {
        return scope.editable = true;
      };
    }
  };
};

angular.module('horus.products').directive('commission', Commission);

Here's what's happening - a new item is added to my list and the template from my directive is compiled, but it throws an error:

TypeError: Cannot set property 'index' of undefined at link () at at nodeLinkFn () at delayedNodeLinkFn () at compositeLinkFn () at publicLinkFn () at boundTranscludeFn () at controllersBoundTransclude () at ngRepeatAction () at Object.$watchCollectionAction [as fn] ()

Any thoughts on why this issue is happening and how I can resolve it? Is there a better way to add a new directive in an ng-repeat?

Answer №1

After some investigation, I finally cracked the code to fix the bug I was facing. It turns out, the issue was stemming from the incorrect definition of the objects I was adding to my array. Silly mistake on my part!

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

Access the value of a variable passed from the view to the controller

Is there a way to retrieve a dynamically generated value from the view to the controller in AngularJS? <ng-option ng-repeat="w in details track by $index"> <div class="program-grid-row table-row" > <div> <a class= ...

How to verify CSRF protection on Node.js/Express endpoints

I have added csrf (cross-site request forgery) protection to my express application like this: ... app.use(express.csrf()); app.use(function (req, res, next) { res.cookie('XSRF-TOKEN', req.csrfToken()); next(); }); ... Everything is working ...

Is there an implicit transformation or action involved when the promise chain is resolved or rejected in $q?

Is there an intrinsic digest/apply included when the promise chain is resolved/rejected in $q? I recently switched from using $q to q in my code and it seems like a digest is no longer happening, leading to different outcomes. What could be causing this c ...

What is the best way to send an array of objects to a Node.js server?

What is the method for sending an array of objects with user data to the server for verification? I am attempting to pass orderform data to a server for validation and then display it on a different page after redirection. const addProductsToServer = (ev ...

Using JavaScript, is there a way to modify a JSON parameter within an API?

My API provides JSON data structured like this: [{"NAME":"john","SURNAME":"johny","ADULT":"3","CHILD":"3","BABY":"0",}] In my JavaScript function, I need to send a request to a web service that will update the value of "BABY" from "0" to "1". Can this be ...

Experiencing the error message "Uncaught TypeError: Cannot read property 'push' of undefined" unexpectedly popping up at random intervals

Hey there, I've encountered an issue while trying to fetch data from a URL and populate it into an array. The process involves pushing the fetched data into the "data" property of each element in the array, and then repeating this process recursively. ...

Looking to gather all property values from an array of objects and store them in individual arrays

Is there a simple way to collect each property value in an array of objects into separate property arrays using underscore or angularjs utilities? For instance, consider the following array of objects: $scope.expNumArray = []; $scope.itemHrArray = []; $s ...

Angular is the best method for properly loading a webpage

Struggling to solve this issue. I have a webpage where I need to load another webpage, specifically a page from a different site, into a div. Essentially, it's like a news ticker that I want to showcase. The problem is that the URL is stored in a Mon ...

Generating Speech from Text using jQuery API in HTML

Can a website be created to detect textbox text upon longClick by the user, and function across various browsers? The site should also have mobile compatibility. Appreciate any help! ...

Encountering a TypeError when implementing $cookies in a controller: undefined function error occurs

UPDATE: RESOLVED ISSUE It turns out that I mistakenly thought ngCookies was a built-in part of angular.js, but in reality it is a separate service. The problem was with my bower.json file which referenced angular 1.4beta while loading angular-cookies for ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Issue with md-stretch-tabs in Angular-Material causing a problem

I am in the process of developing an Angular-based application. ISSUE: I included md-stretch-tabs in my md-tabs element, but when I switch to tab#2, the tab retracts as if there is not enough space to flex. Is this problem related to dependencies or the c ...

Retrieve all references to child elements in React

I am working on a component that renders dynamic children, and I need to assign a unique ref to each child (e.g. ref={'childID' + index}) After the children have been loaded, I am looking for a way to loop through them and access their refs. Is ...

I have encountered an issue with my rows breaking improperly when viewing them in a PDF format, particularly when I include a minus

Whenever I try to view my HTML page in PDF form, I encounter an issue. The problem arises when the numerical values are too large, causing a line break between the minus sign and the values. Here is an example of the HTML page which appears perfectly: ent ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

Mocking `window.location.reload` in unit tests - "Looks like your tests triggered a full page refresh!"

In one of my controllers, I have the following code snippet: $scope.foo = function(){ return RolesService.remove({ data: role }) .then(function (v) { if (!(v && v.cdtError)) { $window.location.reload( ...

"Triggering an event after selecting and opening a file with an input of type file

Check out this snippet of HTML code: <input type="file" id="mysignature_upload" onChange="readURL();"/> We also have some Javascript code: function readURL(){ alert("Hello"); } A potential issue with this code is that the function readURL is on ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

In the realm of jQuery, erasing dynamically generated elements across multiple elements sharing the same index is a task

Currently, I am enhancing the select box dropdown and list of new fonts by adding custom font names. In addition to this, I also want to incorporate a feature for deleting fonts. For instance, when I delete font A from the list (which is currently functio ...

Disable the stack label in a specific column of a stacked column chart using Highcharts

Looking at this stacked column graph in the fiddle link, you'll notice that one column is in grey color to indicate that it is disabled. I am trying to figure out how to hide the total from the top of the column that is grey or belongs to the 'Pe ...