Navigating a list using AngularJS within an HTML view: tips and tricks!

Implementing AngularJS within the context of the Ionic framework. The $scope on the front-end consists of:

  1. an object User that contains a list of sports:

    $scope.user = { sports: { "running": true, "football": true } }

  2. a list named "matches" containing users and their respective sports. For example:

    matches = { userA: {..., sports: {"running": true, "football": true} }, userB: {..., sports: {"rugby": true, "football": true} }

Within the front-end:

<ion-item class="item-thumbnail-left" ng-repeat="match in matches track by match.user.uid">
  <img>
  <span>{{match.user.firstname}} {{match.user.lastname}}</span>
  <h3>{{match.user.position}} - {{match.user.lob}}</h3>
  <h3>@{{match.company}}</h3>
  <h4>{{match.score}} sport(s): </h4>
  <h4 ng-repeat="sport in match.user.sports track by sport.id" style="float: left;">
    {{sport.name}}
  </h4>
</ion-item>

I am aiming to visually emphasize the shared sports between $scope.user and each $scope.matches.user (e.g. highlighting them in red).

Any suggestions on how I could achieve this?

Thank you

Answer №1

Manipulating the DOM can be efficiently done by creating a directive that seems to be the most suitable option. A directive can be designed to receive both $scope.user and $scope.matches.user, allowing for the application of highlights to common elements.

Another method to consider is utilizing the ng-class directive to apply highlights depending on an expression.

Answer №2

To streamline the management of matches in ng-repeat, consider converting it into an array of objects...

matches = [{user: {}, sports: {"running": true, "football": true} }, {user: {}, sports: {"rugby": true, "football": true}]

Next, assign a class based on your uid to the current user...

  <ion-item class="item-thumbnail-left" ng-repeat="match in matches track by match.user.uid"
   ng-class="{'some-class-to-add-highlight': match.user.uid == user.uid}">
   <img>
   <span>{{match.user.firstname}} {{match.user.lastname}}</span>
   <h3>{{match.user.position}} - {{match.user.lob}}</h3>
   <h3>@{{match.company}}</h3>
   <h4>{{match.score}} sport(s): </h4>
   <h4 ng-repeat="sport in match.user.sports track by sport.id" style="float: left;">
      {{sport.name}}
   </h4>
</ion-item>

Answer №3

It is essential to handle these tasks within the Controller. Business logic should not be placed in Angular Views.

function UserCtrl($scope, user, users) {
  $scope.user = user;
  $scope.users = users;
  
  
  $scope.commonSports = Object
    .keys(users)
    .reduce(function(res, username, index) {
      var sports = users[username].sports;
      var common = {};
    
      for(var sport in sports) {
        if(!sports.hasOwnProperty(sport)) { 
          continue;
        }
        
        
        common[sport] = !!(sports[sport] &&
          user.sports[sport])
        ;
      }
    
      res[username] = common;
      return res;
    }, {})
  ;
  
}

angular
  .module('test', [])
  .value('user', { 
    sports: { "running": true, "football": true } 
  })
  .value('users', { 
    userA: {
      sports: {"running": true, "football": true} 
    }, 
    userB: {
      sports: {"rugby": true, "football": true} 
    }
  })
  .controller("UserCtrl", UserCtrl)
;
.highlight {
  background: yellow;
}

li span {
  display: inline-block;
  margin: 5px;
  padding: 2px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<section ng-app="test">
  <article ng-controller="UserCtrl">
  
  <div>
    <h3>You</h3>
    <ul>
      <li ng-repeat="(sport, v) in user.sports">
        <span ng-bind="sport"></span>
      </li>
    </ul>
  </div>
    
  <div>
    <h3>They</h3>
    <ul>
      <li ng-repeat="(user, sports) in commonSports">
        <strong ng-bind="user"></strong>:
        <span 
              ng-repeat="(sport, isCommon) in sports"
              ng-bind="sport"
              ng-class="{highlight: isCommon}">
        </span>
        
      </li>
    </ul>
  </div>
    
    <hr /> 
<pre><code>
{{ commonSports | json }}
</code></pre>
    
  </article>
</section>

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

Draggable resizing of the Accordion component in React.js using Material-UI

In the visual representation, there are two Accordions—one positioned on the left (30%) and the other on the right (70%). Upon clicking the button, the right accordion disappears, while the one on the left expands to cover the full width (100%). A featu ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...

Selenium is throwing an ElementNotInteractableError indicating that the element is not able to be

Today I decided to dive into learning Selenium, but I've hit a roadblock while trying to click on an element that looks like this: <a rel="nofollow" style="" href="javascript:void(0);" time="" itemid="15 ...

Updating the quantity of a product within a state in React allows for easy manipulation of that

My scenario involved attempting to reduce the quantity of a product object in the UI by clicking a button, but the quantity did not update as expected. What is the recommended course of action in situations like this? let product={ a:1,b:2,c:3}; For examp ...

How can I implement a page switch in vuejs by clicking on a name in a table list?

I'm currently working on a list page in VueJS and facing some challenges. Here is the code snippet: <template> <vue-good-table :columns="columns" :rows="row" :search-options="{ ...

When iterating through HTML Elements using the forEach method, the getElementsByClassName function is not capable of targeting these specific elements

Allow me to elaborate, although you will grasp the concept better once you see the actual code. I am retrieving my div elements using the getElementsByClassName function and then converting them into an array using Array.from(). As I iterate through this a ...

Secure API Calls with Prismic while Keeping Access Tokens Hidden

As I delve into the world of building a Vue.js web app, I find myself faced with the challenge of making calls to my Prismic repository without exposing my access token. The Rest API approach outlined here seems promising, but I'm at a loss on how to ...

rails/jquery/ajax: The completion function is not being triggered

My code was functioning correctly without any errors when making an AJAX call that didn't require a return value. In my Javascript (specifically coffeescript), I had the following: $.ajax({ url: "/images/" + image_id + "/" + action, type ...

Utilize Redux Toolkit to efficiently share actions across different slices of state

How can I efficiently share common actions across multiple redux state slices? For instance, let's say I have an updateField action that I want to use in various slices other than just the profile slice. Should I import it from an external file for r ...

Develop a custom script function for every instance of a @foreach loop

I have a challenge where I need to style automatically generated table rows by clicking on a button. Currently, my code appears as follows: @foreach($tours as $tour) <tr id="{{$tour->id}}"> <td> {{$tour->tournr}} &l ...

The functionality of Ajax is limited when it comes to handling multiple div elements at the same

Seemingly silly question ahead, but I've been grappling with it for days to no avail. If anyone can help me solve this, please state your price and provide your PayPal details – the money is yours :). What I'm trying to achieve is to add a "Add ...

Using TypeScript for Routing in Angular

I encountered an error message that says the module 'route' is not available. I'm not sure why this is happening, any thoughts? "Uncaught Error: [$injector:nomod] Module 'route' is not available! You either misspelled the module n ...

Is there a way to incorporate TypeScript type definitions into a JavaScript module without fully transitioning to TypeScript?

Although the title may be a bit confusing, it encapsulates my query in a succinct manner. So, here's what I'm aiming to achieve: I currently have an npm module written in JavaScript, not TypeScript. Some of the users of this module prefer using ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...

Creating a function in a JavaScript module that can be exported to the window namespace

One of the goals of modules is to protect variables and functions defined inside from being accessed outside the script. However, if you want to export a specific function for global use, there are ways to accomplish this. Merely assigning it to the window ...

Utilizing typesafe trpc in Node.js to efficiently transfer data between routes

I have successfully implemented an end-to-end typesafe API using the T3 Stack and can access all the data and types in my Next.js app. However, I also have a Node.js backend to populate my database with. My Node.js setup is as follows: app.use( '/t ...

Having trouble updating the route with the $location service, even after attempting to use $scope.apply

After trying to utilize the location service with no success, I am left wondering why my view isn't changing even after using either $scope.$apply() or $scope.apply. Prior to posting my question, I conducted thorough research on similar inquiries but ...

Monitoring Clicks within an Iframe

Is there a way to track a click event on a hyperlink within an iframe using Google Analytics? The iframe is located within the same domain as the main page. How can this be achieved? The iframe is added dynamically to the page after it has loaded. Is i ...

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...