Adding external data to an ng-repeat scope in AngularJS

Encountering a problem with AngularJS ng-view and ng-repeat, specifically related to managing the scope. Using ng-repeat to display a list of items from an array, with a button outside the ng-repeat scope triggering an array update on ng-click. However, unable to get this functionality to work correctly. Below is a snippet of the code:

<!-- home.html partial -->
<h1>Home view</h1>
<div>
  <ul ng-repeat="p in posts.data">
    <li>{{p.title}}</li>
  </ul>
  <a href="#" ng-click="updatePosts(5)">More</a>
</div>

Controller bound to this partial file:

var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider){
  $routeProvider
    .when('/', {
      controller: 'testController',
      templateUrl: 'home.html'
    })
    .otherwise({ redirectTo: '/' });
});

app.controller('testController', 
  [
    '$scope', 
    function ($scope) 
    {
      $scope.posts = {
        data : []
      };
      $scope.getPosts = function(count)
      {
        for(i =0; i<count; ++i)
        {
          $scope.posts.data.push({title : "Title-"+i})
        }
      }
      $scope.updatePosts = function(count)
      {
        var offset = $scope.posts.data.length;
        var data = [];
        for(i =offset; i<offset+count; ++i)
        {
          data.push({title : "Title-"+i});
        }
        $scope.posts.data = $scope.posts.data.concat(data)
      }
      $scope.getPosts(5);
    }
  ]
);

Desired functionality is for the controller to fetch snippets of data upon clicking "More" and update the view accordingly. For example, transitioning from (1) to (2) when clicking "More". However, always stuck at (1) without progress.


(1)

Home View

  • Title-0
  • Title-1
  • Title-2
  • Title-3
  • Title-4

More

(2)

Home View

  • Title-0
  • Title-1
  • Title-2
  • Title-3
  • Title-4
  • Title-5
  • Title-6
  • Title-7
  • Title-8
  • Title-9

More

Code example also available on Plnkr here

** update** Tried the same code without ng-view and it functioned as expected. Issue seems to stem from usage of ng-view. Example setup without ng-view on Plnkr here

Answer №1

Your solution is almost perfect.

The only issue is that when you use <a href="#" ..., it triggers a redirect to the default page, causing your controller to reload and resetting the post count to 5.

In Angular, if you want to style an <a> element like an anchor tag but prevent default click behavior, simply use href="".

Answer №2

What's happening here is that the default click action is not being prevented when using the # href, causing the view to refresh because the route represented by # alone does not exist

You can confirm this by logging to the console from your getPosts function.

There are a few ways to work around this issue:

  • Remove the href and set CSS cursor:pointer if you want it to behave the same
  • Keep the href as is and pass $event into the function as an argument, then use $event.preventDefault()
  • Change the href to an empty string

Here's a working version without the href attribute

By the way, this issue is all within Angular, since you are using ng-click... it's not an external event

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

Press Button to Modify AngularUI

I am currently facing an issue with creating 6 selectable buttons. It seems that I can only add two buttons successfully, as the third button ends up selecting other buttons and all the buttons get deselected when clicked twice. This is not the behavior ...

Step-by-step guide on dynamically fetching additional images from a directory using php, jquery, and ajax

I have a scenario where I have multiple folders, each containing up to 20 images. On my HTML page, I want to display the first 5 images and provide a "click to view more" option to show the remaining 15 images when clicked. Currently, the issue I am facin ...

Exploring the history and present state of Vue lifecycle hooks

Is there a way to access previous and current data in the updated lifecycle hook in Vue, similar to React? I want to be able to scroll a list of elements to the very bottom, but for this I need: The already rendered updated DOM (to calculate the scroll) ...

Multiple file uploads are causing the issue of req.file being undefined

After going through all the suggested solutions, I am still struggling to identify the root cause of my issue. The problem arises when trying to upload multiple files and form inputs - the req.file is always undefined and the image data ends up in the req. ...

Tips for mocking a particular http resource (URL) solely in Angular

I'm part of a team with front-end and back-end developers. At times, the front-end team needs to make REST requests to an http address or REST-resource that hasn't been implemented yet. Within ngMockE2E, I've come across the $httpBackend se ...

How can one adhere to Angular's recommendation of "always using dots with ngModel" while working within isolate scopes?

Currently, I am working on developing an Angular application utilizing Bootstrap. To reduce the impact of Bootstrap on my HTML code, I have implemented two directives specifically for forms: form-control.js module.directive('formControl', func ...

What is the best way to add a new row to an existing CSV file using json2csv in Node.js?

I need to append a new row to an existing CSV file. If the CSV file already exists, I want to add the new row after the last existing row without adding a column header. Here is the code snippet that I have been using: var fields = ['total', &a ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

Tips for creating a 360 x 235 degree FOV image using three.js

My camera captures round images with a 235-degree field of view, like this one: https://i.sstatic.net/qNfrX.jpg I am familiar with threejs and have successfully rendered 360x360 images as equirectangular projections. However, I want to use threejs to rend ...

Guidelines on resolving the issue of Unsupported platform for [email protected]: requested {"os":"darwin","arch":"any"} (existing: {"os":"win32","arch":"x64"})

Trying to install Parallelshell but encountering a persistent warning. I've checked the package file multiple times without finding a solution. Can someone assist me with this issue? ...

EasyWaySaveArchive in ninja training - mastering the art of retrieving components

Recently started learning about dojo and JavaScript in general. I am currently working on a code snippet that requires a button to change based on the result of a php database query. The PHP script is already complete, and the code I am using so far looks ...

Exploring various layers of nested data

I am currently developing a comprehensive global data storage system for my application (specifically an Angular JS app - although this question pertains to JavaScript in general). I have established a 'service' that is responsible for setting t ...

Is there a way to navigate to a different page in AngularJS without the need to refresh the current page?

I am searching for a method to redirect to a different page without reloading the current one. Let me describe my scenario. I have a user login requirement. If a user is not logged in and tries to access the URL directly (e.g. "localhost/sample.html") th ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

Error: Attempting to subscribe to a post request returned a null result

Every time I attempt to subscribe to a post request, the TypeError: result is null is returned My setup involves an Angular CLI connecting with a Spring Boot application for a simple login page. My goal is to save the response header in local storage. Be ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

Polymerfire: Unable to locate a default bucket

Having an issue with uploading data to the storage Bucket of my app. The line var uploadRef = firebase.storage().ref(); is triggering this error message: Firebase Storage: No default bucket found. Ensure the 'storageBucket' property is set when ...

Utilizing third party (jQuery) with AngularJS $compile

Currently, I am integrating angularjs into a website that is already using jquery to load content asynchronously. The content is loaded and then appended to the DOM using jQuery instead of AngularJS. Here is an example of what I have: function loadConte ...

Issue with parsing JSONP using jQuery's AJAX request

I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...