Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below:

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="bootstrap.min.css" />
    <script src="angular.min.js"></script>
    <script src="script1.js"></script>
  </head>

  <body ng-app="AddNewTest" ng-controller="AddNewController">
    <div class="items" ng-repeat="row in rows">
      <add-new-row data="row" index="$index"></add-new-row>
    </div>
  </body>

</html>

The above directive is defined as shown here:

angular.module('AddNewTest', []).
directive('addNewRow', function ($timeout) {
  return {
    controller: 'AddNewController',
    link: function (scope, element, attribute) {
      element.on('keyup', function(event){
        if(scope.index + 1 == scope.rows.length) {
          console.log('keyup happening');
          $timeout(function () {
            scope.rows.push({ value: '' });
            scope.$apply();
          });
        }
      })
    },
    restrict: 'E',
    replace: true,
    scope: {
      index: '='
    },
    template: '<div class="add-new"><input type="text" placeholder="{{index}}" ng-model="value" /></div>'
  }
}).
controller('AddNewController', function ($scope, $timeout) {
  $scope.rows = [
    { value: '' }
  ];
});

However, despite adding a new row and using $apply(), the ng-repeat does not render the newly added data. Assistance would be greatly appreciated.

Link to Plunker Here

Answer №1

Ensure that you pass an array of rows to the directive in the following manner:-

 scope: {
  index: '=',
  rows :'='
},

<add-new-row rows="rows"  index="$index"></add-new-row>

Check out this working example

Answer №2

With each ng-repeat, you are creating an isolated scope where you can declare a separate directive with its own controller. By doing so, you avoid getting lost in the $scope soup :)

Personally, I prefer to create a clean and independent directive that has its own controller.

angular.module('AddNewTest', []).
directive('addNewRow', function () {
  return {
    restrict: 'E',
    controller: MyController,
    controllerAs: '$ctrl',
    template: '{{$ctrl.rows.length}}<div class="add-new"><pre>{{$ctrl.rows | json}}</pre><input type="text" placeholder="0" ng-model="value" /></div>'
  }
}).
controller('MyController', MyController);

function MyController($scope) {
  var vm = this;
  this.rows = [ { value: '' } ];

   $scope.$watch("value",function(value){
     if(value)
      vm.rows.push({ value: value });
   });
}

http://plnkr.co/edit/AvjXWWKMz0RKSwvYNt6a?p=preview

If needed, you can still bind data to the directive using bindToController instead of using scope:{} and include an ng-repeat directly in the directive template.

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

Waiting for the listener script to finish its task in an Ajax call and then informing the user

I have developed a unique program that allows users to submit test cases from a specific webpage (main.php). The webpage triggers an ajax request to insert user data into MySQL using the file insert.php, with the value done=0. Subsequently, there is a list ...

Uh oh! An error occurred while trying to create the ngFileUpload module

After using NuGet to install Angular File Upload 12.2.13, I made sure to inject the dependencies correctly. However, despite this, I keep encountering the following error: angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module c ...

My code to hide the popup when clicking outside doesn't seem to be working. Can you help me figure out why?

After searching around on stackoverflow, I stumbled upon a solution that worked for me: jQuery(document).mouseup(function (e){ var container = jQuery(".quick-info"); if (container.has(e.target).length === 0) { container.hide(); } }); ...

Bringing in Vue from 'vue' allows for the incorporation of 'different' Vue to diverse documents

This issue involves the interaction between Webpack, ES6 import syntax, and Vue. Currently, I am working on a Vuex mutation that is responsible for adding a new key-value pair mykey: [] to an object within the state. To ensure reactivity, I need to use Vu ...

Updating variable values in AngularJS while navigating through routes

How can I dynamically set the flag icon inside the page header based on the selected language using AngularJS? The language selection is done in a separate .htm file and all managed by AngularJS routing. My application has a single controller called "appCo ...

Clone the children of an li element using jQuery, modify the text within a child tag, and then add it to

I have some awesome CSS that I want to recycle within a <ul>. My plan is to duplicate an existing <li> (to leverage the CSS), modify a <p> element, and then add it at the end of the <ul>. I believe I can achieve this by locating... ...

This method or property is not supported by the object - How to call an Applet in Internet Explorer 9

cmd > java -version Java Version : "1.7.0_11" (Updated) Java(TM) SE Runtime Environment (build 1.7.0_11-b21) Java HotSpot(TM) Client VM (build 23.6-b04, mixed mode, sharing) browsers = IE7,IE8,IE9 (The functionality works smoothly in Google Chrome and ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

Issue: Unable to redirect to 'login' page from 'app.home' state

I am in the process of converting a website into a mobile application, but I have encountered an issue. I am utilizing authO for third-party authentication, and when attempting to log in to the app, I received the following error: Error: Could not resol ...

Incorporating PHP in JS/jQuery AJAX for creating unique odd and even conditional layouts

My PHP code includes a loop that changes the layout of elements based on whether the $count variable is odd or even. For odd counts, an image appears on the left and text on the right. For even counts, it's the other way around. To load content dynam ...

Verify the presence of an image

I have a code snippet that I use to refresh an image in the browser. However, I want to enhance this code so that it first checks if the image exists before displaying it. If the image does not exist, I want to display the previous version of the picture i ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

How can you extract elements from a JSON array into separate variables based on a specific property value within each element?

In the following JSON array, each item has a category property that determines its grouping. I need to split this array into separate JSON arrays based on the category property of each item. The goal is to extract all items with the category set to person ...

Find the most recent date in a file and display the line associated with it

I am working with a document named Application.txt that consists of multiple columns and rows as shown below: ApplNo DocsURL DocDate 4782 www…. 7/28/2003 4782 www…. 11/23/2008 4782 www…. 3/24/2012 5010 www…. 4/5/2003 5010 ww ...

The DOM fails to reflect changes in the data variable in VueJS

I am facing an issue while trying to update an array of arrays and display it as a reactive variable, however the DOM does not seem to reflect those changes. To achieve this, I have two components - a parent component and a child component: Parent Compon ...

Executing `removeChild` within a timeout during page load does not yield the expected results

I have an HTML div that is designed to contain dynamically generated children. These children are meant to be removed from the list after a specific amount of time (e.g. 1000 ms). Although some people have experienced scope issues with timeout functions, ...

HTML with an intricate and dynamic table layout

I am attempting to design a dynamic table that looks like the one shown in this image: https://i.stack.imgur.com/0Bmur.png The challenges I face in creating this HTML table are as follows: It needs to be dynamic as it will display data from a database T ...

Attempting to retrieve an array within a Mustache JavaScript template

I'm attempting to retrieve data from a mustache array using this.location.coordinates.0: <div class="block"> <label>Location (longitude/latitude):</label> {{location.coordinates.0}}/{{location.coordinates.1}} </d ...