Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below:

<!DOCTYPE html>
<html>
<head>
    <title>Directive test</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', []);

        app.controller('mainCTRL', function($scope) {});

        app.directive('listItems', function() {
            return {
                restrict : 'E',
                transclude : true, 
                scope : {
                    items : '='
                },
                controller : function($scope) {
                    /**
                    * @param item item being inserted
                    */
                    $scope.addQuestion = function() {
                        //Define the item list (if undefined)
                        if(!$scope.listOfItems) $scope.listOfItems = [];
                        //add the item
                        $scope.listOfItems.push({
                            question : $scope.question
                        }); 

                        console.log($scope.listOfItems);
                    };
                },
                template : '<div>Question: <input type="text" ng-model="question" />' + 
                                '<button ng-click="addQuestion()">Add question</button>' + 
                                '<div><ng-transclude></ng-transclude></div>' +
                            '</div>'
            };
        });
    </script>
</head>
<body ng-app="myApp" ng-controller="mainCTRL">
  <list-items items="listOfItems">
    <div ng-repeat="item in listOfItems track by $index">
        {{item.question}}
    </div>
  </list-items>
</body>
</html>

I have managed to push objects into the array successfully, but for some reason, they do not repeat as expected. Any ideas why this might be happening?

 <list-items items="listOfItems">
    <div ng-repeat="item in listOfItems track by $index">
        {{item.question}}
    </div>
  </list-items>

Your help is greatly appreciated.

Answer №1

When you assign items in the scope, make sure to use that variable name consistently. In this case, you have used listOfItems in the directive's controller which should be changed to items for it to work correctly.

(function (app, ng) {
  'use strict';

  app.controller('mainCTRL', function($scope) {});

  app.directive('listItems', function() {
    return {
      restrict : 'E',
      transclude : true,
      scope : {
        items : '='
      },
      controller : function($scope) {
        /**
         * @param item item being inserted
         */
        $scope.addQuestion = function() {
          //Define the item list (if undefined)
          if(!$scope.items) $scope.items = [];
          //add the item
          $scope.items.push({
            question : $scope.question
          });

          console.log($scope.items);
        };
      },
      template : '<div>Question: <input type="text" ng-model="question" />' +
                 '<button ng-click="addQuestion()">Add question</button>' +
                 '<div><ng-transclude></ng-transclude></div>' +
      '</div>'
    };
  });
}(angular.module('app', []), angular));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<div ng-app="app" ng-controller="mainCTRL">
  <list-items items="listOfItems">
    <div ng-repeat="item in listOfItems track by $index">
      {{item.question}}
    </div>
  </list-items>
</div>

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

Changing from system mode to dark mode or light mode

Within my Next.js web application, I am implementing MUI to facilitate the transition between system, light, and dark modes. Persistence between sessions is achieved by storing the selected theme in local storage. The user has the option to change the them ...

Having trouble with ui-sref functionality within a Bootstrap dropdown menu

In the header.html file, I have the following angular code: <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> &l ...

The PHP time search function is experiencing technical difficulties and is not functioning correctly

I'm experiencing issues with adding a time search feature to my PHP site. The date search is functioning correctly, but when attempting to incorporate the time search, it doesn't seem to be working as expected. For instance, selecting 13:00 as t ...

Adjust the default value of the ng-model for an input field with a date picker

One of my inputs has a datepicker attached to it. <input id="start-date" style="width: 230px;" close-text="Close" type="text" ng-model="startDate" datepicker-popup="dd-MM-yyyy" ng-required="true"/></div> When the input is displayed, I nee ...

Conceal and reveal buttons at the same location on an HTML webpage

There are 3 buttons on my custom page called page.php: <input type="submit" value="Btn 1" id="btn1"> <input type="submit" value="Btn 2" id="btn2" onClick="action();> <input type="submit" value="Btn 3" id="btn3" onClick="action();> ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...

Issues encountered when trying to use ng-repeat alongside a multiselect plugin

<select class="form_control" id="district" name="district" multiple ng-model="$scope.district"> <option value="{{tp_id}}" ng-repeat="tp_id in district" >{{tp_id}} </option> </select> I am facing an issue where no v ...

What could be causing the embedded dropdown to automatically select the initial option every time?

I am encountering an issue with a page that includes an html table rendered using node with express and ejs. The table contains a select dropdown in one of the cells, and it populates correctly with the right values. However, regardless of which option I ...

Steps for converting an HTML form into a sophisticated JavaScript object

Is it possible to transform a form into a complex JavaScript object based on a structured form layout? I am not sure if there is a better way to accomplish this, but essentially what I am looking for is the following scenario: <form> <input n ...

Issue: When calling setState(...), you must provide either an object containing the state variables to update or a function that will return an object with the updated

Encountering an error in the else section with this.state.incorrect + 1 and this.state.correct + 1 I've come across a similar issue that wasn't resolved by visiting this link: React Native: setState(...): takes an object of state variables to up ...

Nested Promises in Angular's $q Library

I'm facing an issue with a function that should return a list of favorite locations. Here's the code snippet in question: When I call LocationsFactory.getFavoriteLocations(), it returns a promise like this: getFavoriteLocations: function() { ...

Click the button to save numerous images at once

We have added two mask images to the page. https://i.sstatic.net/uAbb7.png When a user clicks on a mask image, a file upload dialog box appears, allowing the user to upload their own image and click save. https://i.sstatic.net/V4kFA.png After clicking ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Combining JSON Files within an AngularJS Service

I utilize a Service in my angular application to retrieve JSON data pertaining to a football team. angular.module('UsersApp').factory('SquadService', ['$http', function($http) { return $http.get('squad/squad-bourne ...

How can I transfer a variable from one webpage to another within the MEAN stack?

This is the Angular View Code: <button class="btn btn-primary" ng-click="edit(obj._id)">Edit</button> Here is the Angular Controller code: $scope.edit=function(id) { console.log('edit() called........'); console.log(id); ...

The response received from the server was a 404 status () indicating that the resource failed to load

I'm encountering an issue while loading from the web service, and receiving the following error: Failed to load resource: the server responded with a status of 404 () Your help would be greatly appreciated. You can also access the code on JSFiddl ...

Guide to implementing dynamic conditional rendering in Vue.js loops (utilizing v-if within v-for)

I am currently working on a table component in a .vue file where I want to display icons based on the direction of the order clicked. For example: <th v-for="(column, index) in columns" :key="index" @click="sort( index )"> <span& ...

Flickering effects in THREE.js using Frame Buffer Objects

I've encountered a strange flickering issue while working on a THREE.js scene that involves using a Frame Buffer Object. The flickering disappears when I comment out the line: mesh.material.uniforms.fboData.value = renderTargetA.texture. THREE.FBO ...

What kinds of data types does MongoDB support in JavaScript?

Regarding the mongodb node client, it allows insertion of JavaScript data using the following syntax: collection.insert({ alpha: 123, bravo: "hello", charlie: [1, 2, 3], }) I am curious to know if mongo supports newer JavaScript data types ...

The Angular 2 rollup AoT compilation results in a larger build size compared to the standard JiT build

I'm facing an issue with reducing the weight of my app during the building process. I am using Angular 2 seed as a starting point. https://github.com/mgechev/angular-seed When I run: npm run build.prod my app.js file size is 1.5MB. However, when I ...