Shift every ng-repeat child element and display the updated outcome

I am looking to create an animation that will shift all items displayed using the ng-repeat directive to the left, hide the first item, and show a new element in place of the last one.

The elements are being displayed using the ng-repeat directive from a JSON object in the controller.

<div class="element" ng-repeat="n in elements | limitTo: 4">
  {{n.title}}
</div>

Although there are 5 elements in the JSON object inside the controller, it is limited to displaying only 4:

$scope.elements = [
  {
    id: 1,
    title: 'title1'
  },
  {
    id: 2,
    title: 'title2'
  },
  {
    id: 3,
    title: 'title3'
  },
  {
    id: 4,
    title: 'title4'
  },
  {
    id: 5,
    title: 'title5'
  }
]

In essence, after clicking the > sign on the right of all elements, my goal is to hide the first one, shift all elements to the left, and reveal a new one on the right.

Can someone provide guidance on how to achieve this? You can find the Plunker I was working on here: https://plnkr.co/edit/dmmrNMaBno3KZMqL8E6O?p=preview

Answer №1

One way to simplify your life is by utilizing an external plugin that specifically caters to this task. However, if you prefer a custom solution, I have managed to create one without relying on jQuery. The magic mainly lies in CSS with some additional functionality in JavaScript. I have encapsulated everything within a directive as all DOM manipulation should ideally be handled within directives. Here's a potential starting point for you:

script.js

var app = angular.module("app", []);
app.controller("mainCtrl", function($scope) {

});
app.directive('elements', function() {
  return {
    restrict: 'E',
    templateUrl: 'element.html',
    link: function($scope, $element, $attrs) {
      $scope.elements = [{
        id: 1,
        title: 'title1'
      }, {
        id: 2,
        title: 'title2'
      },
      // Remaining elements omitted for brevity
      ]
      
      let elementPos = 0;

      $scope.moveSlide = () => {
        elementPos+=4;
        document.querySelectorAll(".element").forEach(elem => {
          let element = angular.element(elem);
          if (elementPos>=$scope.elements.length){
            document.querySelectorAll(".element").forEach(elem => angular.element(elem).css('margin-left', '15px'));
            elementPos=0;
            return;
          }else if (elementPos >= element.attr('order')){
            element.css('margin-left', '-100px');  
          }
        });

      }
    }
  }
});

element.html

<div class="left-arrow"> &lt; </div>
<div class="container">
  <div class="element-container" style="width:{{elements.length*115}}px">
    <div class="element" order="{{$index+1}}" ng-repeat="n in elements">
      {{n.title}}
    </div>
  </div>
</div>
<div class="right-arrow" ng-click="moveSlide()"> &gt; </div>

index.html

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="app" >
  <h1>Hello Plunker!</h1>
  <elements></elements>


</body>

</html>

style.css

.element {
  width: 100px;
  height: 100px;
  background: orange;
  margin-left: 15px;
  display: inline-block;
  transition: 1s all;
}

.container {
  display: inline-block;
  padding: 10px 0;
  height: 100px;
  width: 475px;
  background: #dfdfdf;
  overflow: hidden;
}

.left-arrow {
  height: 20px;
  display: inline-block;
  position: relative;
  width: 20px;
  cursor:pointer;
  top:-50px;
}

.right-arrow {
  height: 20px;
  display: inline-block;
  position: relative;
  width: 20px;
  cursor:pointer;
  top:-50px;
}

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

Setting a JavaScript variable to null

Using Jquery, I have a variable that is assigned a value on button click. After the code executes successfully, I need to reset the variable to null. $("#btnAdd").click(function () { var myDataVariable= {}; myDataVariable.dataOne="SomeDa ...

Display the child component exclusively after the data has been successfully loaded

Within my parent component, I have the following structure: <v-container fluid> <ResultsPanel ref="results" /> </v-container> The ResultsPanel component consists of: <template v-if="showResults"> <v-container > IM SHOW ...

jQuery ajax doesn't function properly on the server, it only works locally

When I send a jQuery Ajax request from my front-end to the back-end to retrieve values for calculations, it works perfectly on my local web server. However, when I try it online, all I get is a result of 0 in my calculations, indicating that the Ajax respo ...

ensure that mocha does not consistently skip tests

When working with mocha, I include several unit tests that incorporate the skip it.skip('login (return photo)', function(done) { ... At times, I need to prevent skipping certain tests, such as right before a deployment. Is there a specific flag ...

Changing text on a button with JavaScript toggle functionality: A step-by-step guide

I am looking to implement a feature where I can hide and show overflow content in a div. When I click on the expand button, it expands the content. However, I want this button to toggle and change text as well. Thank you! function descriptionHeightMo ...

Having trouble loading mtl file in Three.js with map_ks and bump instructions?

I am currently working with an MTL file that contains the following specifications: newmtl blinn_backSG illum 4 Kd 0.17 0.15 0.28 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 bump -s 0.1 0.1 canvas_specular.tif -bm 0.025 Ni 1.00 Ks 0.00 0.00 0.00 map_Ks -s 0.1 0.1 ...

Unavailability of dates in Json ajax DatePicker

After retrieving database records of dates and converting them into a JSON Object, I am attempting to pass the JSON to javascript. The goal is to make the DatePicker UI dynamic by marking the dates in the JSON as unavailable on the calendar. Unfortunately ...

Angular JS Touch and Swipe: Interactive Gestures for Enhanced User

Currently venturing into the world of Angular JS as I dive into developing a mobile application. One essential task at hand is creating a service that can manage touch events such as swipe-left, swipe-right, swipe-up, and swipe-down, with corresponding c ...

Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the ...

The .removeAttr('checked') method fails to function as expected

I am currently using CodeIgniter. Check out this example of my code. Please fill the textbox and check the checkbox next to it, then click on the "add" link. You will notice that it does not work as expected..removeAttr('checked') newDiv.find(&a ...

It appears that the query parameters are impacting the speed at which the page loads

I am currently developing a project on this platform. It is using c9.io, an innovative browser-based collaborative programming IDE. The index.php file includes the following script: <?php $path = ltrim($_SERVER['REQUEST_URI'], '/&ap ...

Ways to execute a GET request including all idRefs

In my project, I have 2 models: stores and products. The stores model has a reference to products like this: produtos: [ { type: mongoose.Schema.ObjectId, ref: 'Produto' } ] Currently, I have an object that looks like this: { "_id": "58971 ...

The data insertion query in MYSQL seems to be malfunctioning

I am facing an issue with inserting data from a form into a database table named "sumation". Despite using PhpStorm IDE, I am getting errors indicating that no data sources are configured to run the SQL and the SQL dialect is not set up. Can anyone help ...

What could be causing the lack of data for the current user?

I have been attempting to fetch the current user session and display the data in the view, but nothing is appearing. I even checked the database and confirmed an active session with all the necessary information. I attempted logging the user out and starti ...

Having trouble retrieving data from a factory in the controller

I'm currently working on my first angular application and running into an issue accessing data in the controller that's coming from a service. The service code looks like this: var BASE= " "; loginApp.factory('authFactory',function ($ ...

Top tips for seamless image transitions

Currently working on a slideshow project and aiming to incorporate smooth subpixel image transitions that involve sliding and resizing, similar to the Ken Burns effect. After researching various techniques used by others, I am curious to learn which ones ...

Deleting an item from a JSON object using Angular

Whenever I click on an item in the list, it generates an input text and adds the attributes of that input to a JSON. Currently, each time I click on an item multiple times, the JSON accumulates all the clicks. For instance, if I click 3 times on the first ...

Guarding against minification of an AngularJS application

I've encountered a problem with minifying my angularjs app for production distribution. I followed the documentation here and used the $inject keyword to prevent Dependency injection issues. However, after the minification process, I'm now facin ...

Creating a shared component for restricting input to only numbers in ReactJS with Material-UI TextField

I am currently working with MUI TextField and my goal is to implement a validation that allows only numbers but not the eE+- keys. I aim to create a standard component for this using onChange event. I need to address the scenario where if the user enters ...

What is causing this code to run immediately upon the addition of Promise logic?

The coding scenario written below was supposed to have two 4-second delays. However, when the code is run, it executes immediately. It seems that there might be a lack of understanding on my part regarding some basic concept, or perhaps there's a hidd ...