Angular Directives: Bringing Clarity to Your Code Base

I have a collection of project items that can be sorted in three different ways: by name, date, or randomly.

When sorted by name or date, the items are grouped by the first letter of the name or the year of the date. However, when sorted randomly, there is no grouping involved, which requires a different structure in the DOM.

Currently, I have implemented two distinct DOM structures in the view, which is not very efficient and may not be the best approach in terms of Angular development practices. I am using directives to toggle between the two DOM templates based on the selected sorting option, but I would appreciate some advice on how to improve this solution.

Update: It is important to note that there are two different implementations of the ng-repeat directive depending on the selected sort option. Sorting by name and date involves a nested loop to iterate through the groups ((header, group) in projects), while sorting randomly only requires a single loop since the items are not grouped (project in projects).

Plunkr. Please observe the delay when you select the Random option. Relevant sections are provided below.

project-grid partial

<div class="project-controls">
    <label><input type="radio" ng-model="orderChoice" value="name">Name</label>
    <label><input type="radio" ng-model="orderChoice" value="date">Date</label>
    <label><input type="radio" ng-model="orderChoice" value="random">Random</label>
</div>

<!-- DOM structure for grouped Name and Date sortings -->
<!-- Note the nested ng-repeat -->
<div id="nonRandomGrouping" ng-hide="randomSort">
    <div class="group" ng-repeat="(header, group) in projects">
        <h2>{{ header }}</h2>
        <ul class="project-thumbnails">
            <li ng-repeat="project in group | orderBy: 'name' ">
            <img ng-src="{{project.coverImage}}">
            <p><strong>{{ project.name }}</strong></p>
            <p><strong>{{ project.date }}</strong></p>
            </li>
        </ul>
    </div>
</div>

<!-- DOM structure for ungrouped Random sorting -->
<!-- Note the single ng-repeat -->
<div class="group" id="randomGrouping" ng-show="randomSort">
    <ul class="project-thumbnails">
        <li ng-repeat="project in projects" style="overflow: auto;">
            <img ng-src="{{project.coverImage}}">
            <p><strong>{{ project.name }}</strong></p>
            <p><strong>{{ project.date }}</strong></p>
        </li>
    </ul>
</div>

controller

angular.module('myApp.controllers', [])
    .controller('MyCtrl1', ['$scope', '$http', function($scope, $http) {
        var projectsByName,
            projectsByYear,
            originalData

        $scope.orderChoice = "name"
        $scope.randomSort = false

        function randomize() {
            $scope.randomSort = true
            $scope.projects = originalData.sort(function() { return 0.5 - Math.random() })
        }

        $scope.getProjects = function() {
          $http({ method : "GET", url : "/projects.json" }).success(function(data) {
              $scope.count = data.length
              originalData = data.sort()
              $scope.projects = projectsByName = _.groupBy(data, function grouper(proj){
                return proj.name[0]
              })
              projectsByYear = _.groupBy(data, function grouper(proj){
                return new Date(proj.date).getFullYear()
              })
          })
        }

        $scope.$watch('orderChoice', function orderChangeHandler(newVal, oldVal){
            if ( newVal !== oldVal ) {
                switch(newVal){
                    case 'name':
                        $scope.randomSort = false
                        $scope.projects = projectsByName
                        break;
                    case 'date':
                        $scope.randomSort = false
                        $scope.projects = projectsByYear
                        break;
                    case 'random':
                        randomize()
                        break;
                }
            }
        })

        $scope.getProjects()
    }])

Answer №1

1. A potential solution could be to represent "Random sort" as a "single grouped" instead of ungrouped to prevent duplication.

2. One alternative approach is to shuffle once instead of repeatedly running it at every watch, and then store the result in memory.

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

Issue with the svg animation not properly "executing"

Hello everyone! This is my debut post, and usually I can find solutions by browsing the community. However, this time I am in need of some assistance. I have crafted an "SVG" file that includes animations depicting the different cycles of a day over a 24-h ...

Is there a way to display just one element without affecting the other elements within the same class?

I need to create a series of buttons that can appear and disappear when clicked. Here's how it should function: When I click on link 1 (link 2 is currently hidden). Link 2 should then become visible. The challenge lies in distinguishing between mu ...

What is the best method for utilizing dynamically assigned keys within a JSON object?

I am currently working with Rhino and I need to find a way to utilize a variable in order to define the key of a map. Here's an example of what I'm trying to achieve: var name = "Ryan"; var relationshipType = "brother"; var relatedName = "David" ...

The navigation in Framework 7 is causing issues with the on-click functionality

Utilizing the framework's built-in formToJSON() function, I have been able to retrieve form values. By utilizing a click event, I am able to log the values. $$("#query-submit").on("click", function () { var queryForm = app.formToJSON("#query-form ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...

Activating a hyperlink within a Div element by clicking on the Div itself

In my card element, I have a link that, when clicked, opens a modal pop-up containing all the necessary project information. I am currently attempting to trigger a click event on that link whenever any part of the div is clicked. This task is for a school ...

fullPage.js with linear scroll

Is there a way to implement fullpage.JS without any transitions between slides? I attempted the following setup, but it didn't work as expected: $('#fullpage').fullpage({ licenseKey: 'XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX', ...

Designing a Curved Stepper Component in the Shape of an S

I've been attempting to create a custom stepper component with an S-curve shape using React, but so far I haven't been successful. I even tried utilizing the MUI Stepper component and experimented with pure HTML and CSS, but couldn't achieve ...

Enabling real-time notifications through Express 4 middleware with socket.io integration

I am in the process of developing a real-time notification system utilizing socket.io. Here is the current server-side code I have implemented: bin/www: var app = require('../app'); var server = http.createServer(app); var io = app.io io.attac ...

Issues with utilizing $http POST

I am a beginner in angular.js and I want to create a form with 2 number fields. When I click on submit, I need to send the data to the server using JSON for calculating the sum. For example, if I input 4 in the first field and 4 in the second field, it sho ...

Why is the Angular directive '=&' value binding to the scope showing as undefined?

An Angular directive has been defined within my application: (function() { 'use strict'; angular .module('almonds') .directive('security', ['$animate', 'AuthFactory', directive]); fun ...

Updating token (JWT) using interceptor in Angular 6

At first, I had a function that checked for the existence of a token and if it wasn't present, redirected the user to the login page. Now, I need to incorporate the logic of token refreshing when it expires using a refresh token. However, I'm enc ...

Steps for Creating an Animation Tool based on the Prototype:

One question that recently came up was: What is the best approach to tackling this issue? Developing a tool that enables designers to customize animations. To make this process easier, it is essential to create an AnimationSequence using JavaScript that ca ...

Having trouble retrieving the value of a textarea within a jQuery UI dialog box

I attempted to place a textarea within a dialog box, with the intention of retrieving the value of that textarea when the "ok" button is clicked. However, I am encountering difficulties in retrieving the value. What could possibly be causing this issue? ...

Whenever a user navigates back to a specific page in Ionic by clicking the back button, make sure to set a variable to null

I've been attempting to set a variable as null whenever a user clicks the back button after signing in. However, my current approach doesn't seem to be working, as the variable still appears on the sign-in page. var currentUserNow = localStorage ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

As soon as I hit the submit button on my website form, the URL is automatically refreshed with the information I provided

I am a beginner when it comes to forms and recently copied and pasted this login snippet code: <div class="login-form-1"> <form id="login-form" class="text-left"> <div class="main-login-form"> <div class="login-group"> ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

Challenges with launching a fresh React App

After installing Nodejs(v 10.16.0 LTS), I used Windows Powershell to execute the following commands: npx create-react-app my-app cd my-app npm start However, I am encountering an issue where my code works properly only when the PowerShell ...

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...