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

Adding controllers dynamically to ng-includes allows for more flexibility and customization in

How can I dynamically change the controller for ng-include in AngularJS? In my application, users can create content pages along with controllers. I am able to adjust the ng-include source dynamically, but I am unsure of how to associate a new controller ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Narrow down an array of objects by matching a specific property and value to a separate array of objects

I am facing a challenge with two sets of arrays - one for the headers (columns) of a table and the other for the rows. const headers = [ { text: 'Dessert (100g serving)', align: 'left', sortable: false, value: 'n ...

Bower consistently installs the most up-to-date version instead of the version that was explicitly specified

Despite the version specified in the "bower.json" file, bower (v1.8.0) doesn't adhere to it and instead downloads the most recent version of the library available. It seems like it's not taking the version into account at all. Even downgrading to ...

Invoke a function within one component using another component

I am facing an issue with deleting playlists displayed on my page. These playlists are fetched from an external API and each playlist has a delete button which is supposed to remove the playlist both from the API and the view. The deletion process works s ...

Error: AngularJS encountered an issue with the HTTP post request, as the OPTIONS failed to return any response

My AngularJS web application typically communicates with the server by sending posts. It has been functioning smoothly until recently. Starting today, I have noticed that most of the time (though not consistently), it encounters an issue during the OPTION ...

Encountering an Issue: The program is throwing a TypeError because it is unable to access properties of null when trying to read '

My goal is to upload an excel file using ng-click and the fileUpload($event) function defined in the app controller scope. I am utilizing xlsx to read the file in JSON format, but I encounter an error when running the code: <div> <input id ...

Assign a value to a locally scoped variable within an iteration in Angular 2

Within my Angular code, I have the following HTML snippet: <span *ngIf="ControllerType?.AttributeID =='Controller Type'"> <select multiple name="ControllerType.Default" [(ngModel)]="Contro ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

Exploring the mechanics of an Ajax call

Feeling a little lost in the call flow of Ajax - can anyone provide some guidance? This is my HTML: <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction()">Change Content</but ...

appearing like a straightforward process of creating strings in JavaScript

Originally, I thought this task would be easy, but it ended up taking me the entire morning! var insert = '<div class="main_content_half_panel_circle" id="circle_' + c + '"></div><script type="text/javascript">$("#circle_& ...

Looking for help understanding a basic piece of code

$('#ID').on('click', function() { if(!CommonUtil.compareDateById('startDt','endDt',false, false, true)) { return false; } var cnt = 0; if(!CommonUtil.isNullOrEmptyById('startD ...

Encountering a 415 Unsupported Media Type error when making a post request to an ASP.NET Core API from an Angular application

Utilizing the code above in an Angular application: function Login(email, password, callback) { var GetAll = new Object(); GetAll.email = email; GetAll.password = email; $http({ url: "http://local ...

While trying to install express using Node.js, an error (error:0906D06C :PEM routines : PEM_read_bio npm) occurred

I recently installed node.js on my computer and npm came along with it. However, when I try to execute "npm install express" in my Windows command prompt, I encounter the following error message. Can anyone guide me on how to resolve this issue? C:\U ...

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnadey/D ...

tips for efficiently using keyboard to navigate through tabs in an unordered list

Utilizing unordered lists in this web application. I am looking to implement tab navigation with keyboard functionality. How can I achieve this? The first tab should contain text boxes, and when the user fills out a text box and presses the tab key, they s ...

How to create a continuous loop for a JavaScript carousel

I have a simple carousel set up with this code. I'm looking to make it loop back to the beginning after reaching the third quote-item. Can anyone provide some guidance? Thank you! This is the JavaScript used: <script> show() $(functi ...

Navigating through Router Parameters in VueJS

Currently, I am in the process of developing a blog using Vue.js and I am still learning the ropes. To explain briefly, I have a list of dynamic elements that are displayed on the screen. When a user clicks on one of these items, I want to navigate to the ...

Using pre-existing code but with personalized modifications

I have several pages containing code for a footer area with buttons and other elements at the bottom: <nav class="navbar navbar-default navbar-fixed-bottom" role="navigation"> <div class="container"> <div class="navbar-inner"> ...