When the page is dynamically loaded, Ng-repeat does not function as expected

I am working on a page that includes the following code snippet:

<script>
angular.module('myapp', []).controller('categoryCtrl', function($scope) {
    $scope.category = <? echo json_encode($myarr); ?>;
    $scope.subcategory = <? echo json_encode($myarr2); ?>;
});
</script>
<div ng-app="myapp" ng-controller="categoryCtrl" id="cate-container">
<div ng-repeat="x in category" class="cate-holder">
<div class="cate-class" onClick="opensubcate(this)">{{x.isim}}</div>
<div class="subcate-holder">
<div ng-repeat="y in subcategory | filter:{kategori:x.isim}" class="subcate-class">{{y.isim}}</div>
</div>

</div>
<div id="list-holder">
</div>
</div>

Using AJAX, I load this page into the #list-holder element.

<script>
angular.module('myapplist', []).controller('listCtrl', function($scope) {
    $scope.list = <? echo json_encode($myarr3); ?>;
});
</script>
<div ng-app="myapplist" ng-controller="listCtrl" id="list-container">
<div ng-repeat="i in list">{{i.isim}}</div>
</div>

While everything else is functioning correctly and displaying data fetched from the database within $scope.list, the directive ng-repeat="i in list" is not rendering the values of {{i.isim}}.

If I access the second page directly, it does show the correct output of i.isim.

The provided AJAX functionality ensures proper loading of content for those who may question its effectiveness =)

$('.subcate-class').click(function(){
        var thissub = $(this).text();
        var thiscate = $(this).parent('.subcate-holder').prev('.cate-class').text();
        $.ajax({
            url:"php/salelist.php",
            data:{kategori:thiscate,altkategori:thissub},
            type:'POST',
            success: function(e){
                $('#list-holder').html(e);
            }
        });
     });

Answer №1

Upon examining your Ajax call, it is now clear where the issue lies. Indeed, the root of the problem stems from this specific Ajax call.

Your mistake lies in attempting to use both jQuery and Angular simultaneously. This combination is not recommended as they are concurrent technologies that function differently. While Angular generates the DOM from data, jQuery manipulates the DOM. Essentially, jQuery fetches data independently, causing Angular to remain unaware and therefore failing to react or update the view accordingly.

Furthermore, loading two libraries instead of one adds unnecessary complexity.

To resolve this issue: either eliminate jQuery and adhere to Angular's methods (utilizing the $http service), or abandon Angular altogether and opt for a strictly jQuery approach.

Answer №2

Pass the values of PHP variables to the ng-init function and then set them as a list.

<div ng-app="myapplist" ng-controller="listCtrl" id="list-container"
  ng-init="loadList('<?php echo json_encode($myarr3); ?>')">

      <div ng-repeat="i in list">{{i.name}}</div>
</div>


angular.module('myapplist', []).controller('listCtrl', function($scope) {
    $scope.list;
    $scope.loadList($scope.list)
});

Answer №3

After conducting thorough research, I was able to identify and resolve the issue at hand. It turned out that the main problem was not with the ajax functionality itself, but rather with having two instances of ng-app. The first instance rendered automatically, while the second one did not render on document onload. Even after attempting to predefine $scope.list and removing ajax entirely, the ng-repeat problem persisted. It became clear that the culprit was the presence of a second ng-app. To tackle this issue, I consolidated the two-page format into one page, removed the second ng-app, and integrated all elements into the first ng-app. Additionally, I decided to utilize $http from Angular instead of $.ajax from jQuery as there was no way to seamlessly transfer the $.ajax response to Angular's $scope.list. The final solution is detailed below:

PS: Notably, the ng-repeat function eliminates the need for any explicit triggering like $apply. When a variable changes, it automatically triggers a re-render.

<script>
angular.module('myapp', []).controller('categoryCtrl', function($scope, $http) {
    $scope.category = <? echo json_encode($myarr); ?>;
    $scope.subcategory = <? echo json_encode($myarr2); ?>;
    $scope.liste;

    $scope.clickfunc = function(e){
        $scope.thissub = $(e).text();
        $scope.thiscate = $(e).parent('.subcate-holder').prev('.cate-class').text();
        $http({
            method : "POST",
            url : "php/salelist.php",
            params:{kategori:$scope.thiscate,altkategori:$scope.thissub}
        }).then(function mySuccess(response) {
            $scope.liste = response.data.list;
        }, function myError(response) {
            $scope.liste = response.statusText;
        });
        }
});
</script>
<div ng-app="myapp" ng-controller="categoryCtrl" id="cate-container">
<div ng-repeat="x in category" class="cate-holder">
<div class="cate-class" onClick="opensubcate(this)">{{x.isim}}</div>
<div class="subcate-holder">
<div ng-repeat="y in subcategory | filter:{kategori:x.isim}" class="subcate-class" ng-click="clickfunc($event.target)" onClick="showem()">{{y.isim}}</div>
</div>

</div>

<div id="list-holder">
<div id="list-container">
<div id="back" onClick="goback()">&lt;</div>
<input type="text" ng-model="filterem" id="filterem" placeholder="Search...">
<table class="product-table">
<tr><th width="31%"></th><th width="10%">Category</th><th width="10%">Subcategory</th><th width="31%">Name</th><th width="7%">Stock</th><th width="11%">Price</th></tr>
</table>
<div id="table-scroll">
<table class="product-table">
<tr ng-repeat="i in liste | filter:filterem" class="product-holder">

<td width="33%"><img src="product/{{i.image}}" class="product-img"></td>
<td width="10%" class="product-cate">{{i.category}}</td>
<td width="10%" class="product-sub">{{i.subcategory}}</td>
<td width="33%" class="product-name" onClick="details(this)">{{i.name}}</td>
<td width="7%" class="product-price">{{i.stock}}</td>
<td width="7%" class="product-stock">{{i.price}} USD</td>
<td style="display:none" width="0" class="feed">{{i.feed}}</td>
<td style="display:none" width="0" class="origin">{{i.origin}}</td>
<td style="display:none" width="0" class="feature">{{i.feature}}</td>

</tr>
</table>
</div>
</div>

</div>

</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

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

I am encountering an issue stating "indexRouter has not been defined"

Encountering an error "indexRouter is not defined" while attempting to run the code below. Despite attempts to remove the line, additional errors persist. Can anyone clarify the rationale behind using the common variable router for both index.js and user.j ...

Looking to incorporate an additional column 'LastName' that can be used for filtering in the Angular data table code. This column will be included if it is present in the data

function applyFilter(filterValue: string) { filterValue = filterValue.toLowerCase(); --- return filtered result return this.dataSet.filter( (item: any) => item.name ? item.name.toLowerCase(). ...

How to incorporate Mixin in your Nuxt template

I'm having trouble utilizing the mixin function in my template. Although Vue documentation states that mixins and components are merged, I am unable to call the function. getImage is not a function Mixin export default { data() { return { ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...

Tips for transferring a JavaScript object to a Node.js server

I must admit, I am positive that the solution to my issue is incredibly simple yet it has been evading me for more than a week now and causing me endless frustration. My current project involves creating a web app for quoting purposes within my workplace, ...

Fill in input field based on choice from the drop-down menu - JavaScript

I am facing an issue where I cannot add text inside the text box based on the dropdown selection. For example, if I select option2 from the dropdown, the textbox should be populated with option2. (function() { 'use strict'; setInterva ...

Click the closest checkbox when the value equals the Jquery datatable

I am facing an issue where I need to add a class and click on a specific element in each row of my jQuery datatable if a certain value is equal. However, I am unable to successfully add the class to that element and trigger a click event. <table id="us ...

After adding data to an empty array, index 0 becomes undefined for someEmptyArray

Currently, I am utilizing fs.readdir to generate an array of filenames within a specific directory. Additionally, I have implemented some regex functions to filter out undesirable filenames and/or filetypes. Upon executing the code provided below, I succe ...

Ways to automatically refresh HTML table in Django framework

How can I dynamically update the search content under the hostname column in an HTML table? The search content needs to be updated every time, and the row number should increase according to the number of hostnames entered by the user. Below is my index.h ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...

Enhancing Animation Speed with jQuery

I've provided the code snippet at this link: http://jsfiddle.net/LnWRL/4/: Here is the HTML: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <div id="wrap_demo"> <div id="demo"></di ...

Is there a way to dynamically insert objects into an array from an ajax json request, in order to iterate through them later on?

I have a current code where I am trying to utilize data to create a new information window from the Google Maps API dynamically. Currently, I am pushing objects of different data types into an array, but I believe that might be the only issue here. How c ...

Fetching various data from MongoDB using NodeJS and presenting it in Jade(Pug) template

I am working with MongoDB collections and need to showcase them on my website, creating a dynamic page that updates automatically. Specifically, I am dealing with team members' information in the database. Here is an example of how my collections loo ...

Is there a way to extract information from an external XML document and incorporate it into an HTML file?

I am attempting to extract information from an XML file that is not stored on my website's server. My goal is to utilize this data for various purposes, such as generating charts. One specific example involves using weather data from an XML file locat ...

"Automatically insert a new row into the table if the cell loses focus and is not left

Can someone assist me with adding a table row dynamically when a cell is filled and the input focus is lost? My JavaScript skills are not strong. Here is a link to the form: JSFIDDLE <table class="table table-timesheet" ng-controller="TimesheetCtrl"> ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

Preventing jQuery from removing child elements while inserting data through ajax

When I try to insert data into an HTML structure using the code below, only one of the elements displays at a time. It seems like when I use Ajax to insert data, the child elements are being removed. How can I prevent this without having to change the stru ...

The byte order of integer literals in JavaScript

When writing the following line in Javascript: var n = 0x1234, is it always true that n == 4660? This question could also be phrased as follows: Does 0x1234 represent a series of bytes with 0x12 as the first byte and 0x34 as the last byte? Or does 0x1234 r ...

How to continuously stream and display an actively updating log text file from a server in real-time onto a web textbox, eliminating the need for webpage

There is a log file in notepad format with values like this: 11.23445646,56.3456578954, 10.23445646,26.3456578954, and 16.23445646,-46.3456578954. I want to retrieve the data from the server and display it in a website textbox. The first value, which is ma ...