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

Displaying entries of input data

I have an application that includes a modal window with filters, but I am looking to add another type of filter. However, I am struggling with implementing it in React and would appreciate any help with the code or recommended links. Essentially, I want t ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

Obtain one option from the two types included in a TypeScript union type

I am working with a union type that consists of two interfaces, IUserInfosLogin and IUserInfosRegister. The TUserInfos type is defined as the union of these two interfaces. export interface IUserInfosLogin { usernameOrEmail: string; password: string; } ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

Using Selenium Webdriver with C# to dynamically expand a RadMenu Webelement in Javascript

I am currently working with Selenium WebDriver in C# and facing an issue with a RadMenu. My goal is to hover over the menu so that it expands a sub menu, where I can find a specific webelement to click. I have tried using JavaScript for this purpose, but u ...

Navigating an Angular JSON object: A guide

I have successfully created a nodejs application that reads all the databases in my mongo Db when I run it in the console. However, I am facing an issue when trying to parse the data into a json object and display it on the screen. If anyone can guide me o ...

The drag functionality can only be used once when applied to two separate div elements

Recently, I came across an issue where I have both an Image and a custom text element placed between them using an input box. My goal is to make both the text and the image draggable on the page. However, I noticed that while the image can be dragged and d ...

Firebase 3 authentication does not maintain persistent login sessions

I recently upgraded my AngularJS app to use Firebase 3.x and AngularFire 2.x for email and password authentication. I referred to the following documentation for migration: https://firebase.google.com/support/guides/firebase-web https://github.com/fi ...

Troubleshooting module not being found with rekuire, requirish, or rfr in resolving relative require problem in nodejs

Looking to steer clear of the complicated relative path problem detailed here by opting for one of the suggested solutions. I've found three similar libraries that could help: rekuire node-rfr aka Require from Root requirish I've experimented ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

Guide on integrating the @nuxtjs/axios plugin with Nuxt3

I'm trying to fetch API data from using this code: <template> <div> </div> </template> <script> definePageMeta({ layout: "products" }) export default { data () { return { data: &apo ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Developing jasmine tests for an Angular directive

When implementing the directive below, it will check and load a template with either "pass", "fail", or "required" as values based on certain conditions. if(parent value == required){ 1. if the value is true -> $scope.msg = "fail" -> loads the templ ...

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

"Implementing jQuery to dynamically set the href attribute for a link when

My website features a tabbed menu that displays content from various WordPress categories including Cars, Trucks, and Buses. The active tab is randomly selected each time the page is reloaded. However, there seems to be an issue with the "View More" button ...

What is the method by which AngularJS retrieves the values for parameters such as data, status, etc?

Forgive me if this is a silly question, but I'm struggling to understand: function login(email, password){ return $http.post('/api/v1/login/', { email: email, password: password }).then(loginSuccessFn, loginError ...

The application experiences a sudden failure when Mongoose is unable to locate the specified item

I am facing an issue where my app crashes when mongoose is unable to find the item. I want to display a 404 error page instead. Here is the code snippet: try { let theBeverage = Product.findOne({ _id: beverageId }); await theBeverage.then((data) ...

Recreate body content with JQuery Mobile

I've been attempting to duplicate the entire HTML content within the tags. However, even though the appearance on screen is correct, none of the links are functioning.</p> <p>To view the fiddle, click here: [Here is a fiddle][1]</p> ...

An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string ...