The ng-repeat directive fails to update data from the model

Can anyone help me figure out why my ng-repeat isn't updating with the data from the array I'm trying to display? Here's a snippet of the HTML code:

<div ng-controller="photoCtrl as c">
        <div ng-repeat="p in c.photos">
            <div>USER: {{p.user_id}}</div><br/>
            <div>PHOTO NAME: {{p.name}}</div><br/>
            <div>PRICE: {{p.price}}</div><br/>
            <hr>
        </div>

        <button ng-click="prev()">Prev</button><input type="number" ng-model="page_nr"><button ng-click="next()">Next</button>
    </div>

Here is the Angular controller code:

    app.controller('photoCtrl', ['$scope', '$window', 'PhotoFactory', function($scope, $window, PhotoFactory){
    $scope.photos = [];
    $scope.page_nr = 0;
    $scope.searchNextFive = function(){
        let toSend = angular.copy($scope.page_nr);
        PhotoFactory.searchNextFive(toSend).then(function(response){
            $scope.photos = angular.copy(response.data);
            console.log($scope.photos);
        });
    };

    $scope.getAll = function(){
        let toSend = angular.copy($scope.user);
        PhotoFactory.getAll(toSend).then(function(response){
            $scope.photos = angular.copy(response.data);
            console.log($scope.photos);
        });
    };
    $scope.prev = function(){
        $scope.page_nr--;
        $scope.searchNextFive();
    };

    $scope.next = function(){
        $scope.page_nr++;
        $scope.searchNextFive();
    };
}]);

Although there are no errors in the code and the 'photos' array does update correctly when changed (as shown by the console.log()), the data is not rendering on the page. Could it be an issue with how ng-repeat is being used on div tags or am I missing something else?

Answer №1

When it comes to your code, you are blending two different methodologies together, assuming that one would function like the other. In this scenario, you have employed the controllerAs pattern where you established a controller alias c using ng-controller="photoCtrl as c". This signifies that you will reveal bindings by linking variables and functions to this (context). However, you ended up attaching these variables and functions to $scope, indicating that there is no need for the controller alias. You can rectify this issue swiftly by removing c. from the variable names in your HTML.

I would highly recommend opting for the controllerAs methodology. The only adjustment required is to eliminate all bindings from scope, initiate a variable at the beginning of your controller named var vm = this;, and then substitute all instances of $scope. with vm..

Furthermore, make amendments to the following lines:

<button ng-click="prev()">Prev</button>
<input type="number" ng-model="page_nr"/>
<button ng-click="next()">Next</button>

as follows:

<button ng-click="c.prev()">Prev</button>
<input type="number" ng-model="c.page_nr"/>
<button ng-click="c.next()">Next</button>

Answer №2

If you decided to implement the scope alone method, a structure like this would suffice:

Here is the modified HTML Code:

<div ng-controller="photoCtrl"> <!--note the change here instead of "photoCtrl as c" we are using "photoCtrl" -->
    <div ng-repeat="p in photos">
        <div>USER: {{p.user_id}}</div><br/>
        <div>PHOTO NAME: {{p.name}}</div><br/>
        <div>PRICE: {{p.price}}</div><br/>
        <hr>
    </div>

    <button ng-click="prev()">Prev</button><input type="number" ng-model="page_nr"><button ng-click="next()">Next</button>
</div>

You do not need to make any changes to the controller code.

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

Sharing JSON data between two Backbone views

Could you provide some guidance on how to pass dynamic JSON data from one view to another? In the initial view, I am creating the JSON object using the following syntax: json.push({ first: value, second: value }); ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

Angular directive within a directive

I'm a beginner in AngularJS and I'm attempting to create a directive that contains another directive inside it. Here is how the first directive looks: ( function () { app.directive("cmEventBar", function () { var controller = func ...

Update the content of an image in a Div without altering its filename

My application's backend updates an image file and sends the filename back to the front-end: $('#giffinal').html(ResponseGo); However, when I update the image again through the backend, the code in the div on the front-end does not change. ...

Node 14 introduces a new feature that allows modules to be imported using absolute paths for native ES6 modules

As I develop an app in node version 14.9.0, the need for importing modules arises. To make the process cleaner and more organized, I have configured my ES6 module with "type": "module" in my package.json. My goal is to implement absolut ...

Troubleshooting a simple test issue with React AXIOS post in an Express environment

I have successfully created a React front end and used a basic boilerplate to connect it with Express. However, I am now faced with the challenge of setting up a simple RESTful API, and the myriad of options available is overwhelming. My goal is to establi ...

Encrypting data using NodeJS Crypto and decrypting it in front-end JavaScript

I'm currently on the hunt for a way to perform AES256 CBC decryption on the client side. When working with nodeJS, I typically utilize this function for encryption: exports.encrypt = function(txt, cryptkey){ var cipher = crypto.createCipher(' ...

Establishing limitations for sap.m.DatePicker

Is there a way to enforce minimum and maximum date constraints on my DatePicker? I want to ensure that if a user selects a date outside the allowed range, it either doesn't trigger a change event or automatically reverts to a valid date. I am using 2 ...

Submitting the form without utilizing Ajax, but instead sending data directly to a PHP script

I've encountered an issue while posting a form to a PHP file using AJAX. Despite my efforts, the form is bypassing AJAX and posting directly to the PHP file. Here is my form: <form id="editform" name="editform" action="ajaxeditform.php" method= ...

Encountered ENOENT error while setting up create-react-app

Recently delved into the world of React by taking an online course on Udemy. However, I encountered a sudden issue with my create-react-app and received this error log. Installing packages. This may take a few minutes. Installing react, react-dom, and ...

Whenever an Ajax request is made to a PHP file, it consistently fails to retrieve any data despite the fact that the

Whenever I try to call a basic PHP page using AJAX, the response is always empty, even though the PHP code itself is functioning correctly. If you visit the URL of the PHP file directly, it echoes "Hello World" as expected. But when accessed from JavaScrip ...

The default date setting in AngularJS directives is malfunctioning

Is there a way to set a default date in a specific id of an HTML element? I am currently using datetimepicker in AngularJS directives, but I'm struggling to set the default date in my id. timeTracker.directive('datetimepicker', function($pa ...

Ways to eliminate the worldwide model in SAPUI5

I've been attempting to break down the global model without success. I have a filter button that's set up like this: navToSecond : function (oEvent){ var oObject = this.getView().byId("inp").getValue(); sap.ui.getCore().setModel( ...

Utilize BotDetect in Angular js for advanced functionality

We are licensed to use BotDetect and now, we want to integrate it with Angular js. After searching on Google, I couldn't find a proper solution but stumbled upon angularjs-captcha, which seemed promising at first but didn't quite help me achieve ...

The ng-token-auth plugin in combination with the ui-router resolver leads to a blank

I have been referring to the ng-token-auth documentation here in an attempt to implement a resolver for authentication using the validateUser function. However, when I add the code snippet provided in the documentation to my app.js file under the "home" st ...

Encountering a problem when trying to send an API request for multer in order to save

I encountered an issue with my node API that uses multer to store files. I am receiving an error when calling it and seeking assistance. Below is the code snippet along with the specific error message - Code - const storage = multer.diskStorage({ d ...

Executing the same function on both mouse click and key press with HTML and JavaScript

I need help figuring out how to call the same JavaScript function whether a user clicks a mouse or presses the enter key. Here is the code I have in my HTML file, but it doesn't seem to be working. Can anyone advise on how to fix this issue? <div ...

Tips on concealing confidential keys within a React.js application on the frontend aspect

Desperate times call for desperate measures - I am attempting to conceal a secret key within my React frontend application. While I understand the risks involved, I feel compelled to do so without any other viable options. The reason behind my actions is ...

Creating an autocomplete select dropdown for United States states in JS/Vue: A step-by-step guide

I am currently working with an array of state objects: states = [ {name: "California", abbreviation: "CA"}, {name: "New York", abbreviation: "NY"}, ] When using browser autocomplete, I have noticed that it functions properly when I set the v-mode ...

Angular.JS - Handling multiple triggers of an event

Snippet: scope.offCanvasShow = function ($event) { $('.app-off-canvas-menu').toggleClass('show'); $event.preventDefault(); $event.stopPropagation(); $(document).one('touchstart click', offCanvasHandler); /** ...