Modify the text of a button depending on the condition and user interaction within an ng-repeat loop in AngularJS

I have a scenario where I am displaying a list of users with two buttons for Start and End using the ng-repeat code:

<div class="list-group" ng-repeat="patient in patients" >
                    <a href="#" class="list-group-item"  ng-click="chatNow(patient.id);" >{{patient.firstname}} {{patient.lastname}}</a> &nbsp;
    <button class="btn btn-success" ng-click="chatNow(patient.id);">{{btnLabel}}</button> &nbsp;
    <button class="btn btn-danger" ng-click="endVideo(patient.appointmentId);">End Consultation</button>
                </div> <!-- list-group ends -->

This list is automatically refreshed every 30 seconds using $http.get.

The btnLabel is initially set to 'Start Consultation' in the Controller:

var t = $scope;
t.btnLabel = 'Start Consultation';

When chatNow is called on ng-click, the btnLabel changes to 'In Progress':

    t.chatNow = function(jobId) {
  t.btnLabel = 'In Progress'; 
 };

Now, I also want the label to change based on the chatStatus property:

{{patient.chatStatus == 22 ? 'Start Consultation':'In Progress'}}

The challenge I am facing is combining both of these conditions so that the label changes on click as well as when there is a change in chatStatus. Any assistance would be highly appreciated.

Thank you for any further pointers.

Answer №1

Take a look at this http://example.com/edit/AbC123XYZ456

Make sure to validate according to your specific requirements

  $scope.updateStatus = function($event){
   $event.target.innerHTML = "Updating"
 }

I hope this information is useful to you.

Answer №2

Give this a try:

$scope.$watch('chatStatus', function(newValue, oldValue) {
    if(newValue != oldValue && newValue == 22) {
        $scope.btnLabel = 'Start Consultation';
    }
});

After a thorough review, here's an updated version for you.

HTML:

<body ng-controller="MainCtrl">
  <div class="list-group" ng-repeat="patient in patients">
    <a href="#" class="list-group-item"  ng-click="chatNow(patient.id);" >{{patient.firstname}} {{patient.lastname}}</a> &nbsp;
    <button ng-init="btnLabel[$index]='Start Consultation'" class="btn btn-success" ng-click="chatNow(patient.id);">{{btnLabel[$index]}}</button> &nbsp;
    <button class="btn btn-danger" ng-click="endVideo(patient.appointmentId);">End Consultation</button>
  </div> <!-- list-group ends -->
  <button ng-click="thirtySecondRefresh(1)">30 Second Refresh</button>
</body>

AngularJS/JavaScript:

app.controller('MainCtrl', function($scope) {
  $scope.btnLabel = [];
  $scope.patients = [
    {id: 21, firstname: 'Tim', lastname: 'Harker', chatStatus: 22},
    {id: 17, firstname: 'Satya', lastname: 'Unknown', chatStatus: 22},
    {id: 75, firstname: 'Stack', lastname: 'Overflow', chatStatus: 22}
  ];
  $scope.chatNow = function(id) {
    $scope.btnLabel[$scope.patients.indexOf($scope.patients.find(x => x.id == id))] = 'In Progress';
  };
  $scope.$watch('patients', function (newValues, oldValues) {
    for (var i = 0; i < newValues.length; i++) {
      if (newValues[i].chatStatus != 22) {
        $scope.btnLabel[i] = 'In Progress';
      }
    }
  }, true);
  $scope.thirtySecondRefresh = function(id) {
    $scope.patients[id].chatStatus = 20; // other than 22
  };
});

Feel free to check out the Plunker for a live demo: http://plnkr.co/edit/Bd6UhU4RwDiYKGhEhR0n?p=preview

I trust this will be of assistance!

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

How do I retrieve the HSL value for a color selected using an input of type 'color' in JavaScript?

I am faced with a creativity block and don't know where to begin. My goal is to develop functions that can manipulate the HSL values once I have access to them. Specifically, I am interested in modifying the light value, which is why I require it in ...

Finding your site's First Contentful Paint (FCP) can be done by analyzing the

After doing some research on Google insights, I came across information about FCP. However, I'm still unsure about how to determine my site's FCP and other relevant metrics. If anyone could provide me with more information or share detailed link ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

In ReactJS, the way to submit a form using OnChange is by utilizing the

Is there a way to submit a form using Onchange without a button? I need to fire the form but can't insert routes as it's a component for multiple clients. My project is built using react hook forms. const handleChange = (e: any) => { c ...

What are the benefits of using `observer` over `inject` when passing data to a React component in MobX?

After reading MobX documentation, it appears that using observer on all components is recommended. However, I have discovered that by utilizing the inject method, I am able to achieve more precise control over which data triggers a re-render of my componen ...

The removal of classList.remove() only eliminates the class itself, not its contents

My goal is to add one class and remove another class when the start quiz button is clicked. While the 'info_box' class is successfully added, the 'start_btn' class does not get removed; it just changes position (from flex to no flex). T ...

Show the value in the input text field if the variable is present, or else show the placeholder text

Is there a ternary operator in Angular 1.2.19 for templates that allows displaying a variable as an input value if it exists, otherwise display the placeholder? Something like this: <input type="text "{{ if phoneNumber ? "value='{{phoneNumber}}&a ...

Avoiding the utilization of HTML forms

Is it acceptable to send form information using jQuery instead of creating an HTML form? By skipping the traditional HTML form and using $.ajax in jQuery, are there any security, performance, or semantic issues to be concerned about? Does this approach a ...

Transferring data from JavaScript to PHP for geolocation feature

Hello everyone, I'm looking to extract the longitude and latitude values from my JavaScript code and assign them to PHP variables $lat and $lng. This way, I can retrieve the city name and use it in my SQL query (query not provided). Below is the scrip ...

Searching for two distinct nested key values in Ramda

I am new to Ramda and wondering if it is possible to retrieve two different key values at the same level of an object. Below is the code I have added: In this scenario, the object 'list' contains keywords 'users' and 'employee&ap ...

Do AngularJS routes allow the use of special characters in URLs?

Issue at hand: Every time I enter http://localhost:53379 in the browser, it redirects me to http://localhost:53379/#/. Why is the /#/ being added? angular .module('app', ['ngRoute', 'ngStorage']) .config([&apo ...

Using data-image as the source for Bootstrap Modal

I am currently working on an image gallery that utilizes the Paver jQuery plugin. The gallery is functional, but I am facing an issue where it displays the same image in the modal instead of showing the respective data-image for each image. My goal is to ...

Troubleshooting a bug in React TypeScript with conditional logic

I have a new message button and a few conversations. When I click on a conversation, the right side should display the message box. Clicking on the new message button should show the create new message box. Here are my useState and handlers: const [newMess ...

What is the best way to retrieve a date (value) from a DatePicker and then set it as a property in an object

I am currently utilizing the react-datepicker library, and I have a question about how to retrieve a value from the DatePicker component and assign it to the date property within the Pick object. Extracting data from regular input fields was straightforw ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...

Creating a personalized Autocomplete feature using React Material-UI with the help of the renderInput method

I'm currently using a React Material UI Autocomplete component, similar to the one in the official documentation. For example, let's consider a list of countries: import * as React from 'react'; import Box from '@mui/material/Box& ...

Adjust input width based on content in VueJS

Is it possible to achieve the following using (Pug & CoffeeScript): input(placeholder="0", v-model.number="order[index]" v-on:change="adjustInput") ... adjustInput: -> event.target.style.width = event.target.value.length + 'ch' Even ...

In React, firebase.firestore() is operational, but firebase.functions() remains undefined

Currently, I am engaged in a React project that heavily relies on Firebase for various features. In order to incorporate HTTPS callable functions into the project, I encountered an issue. The problem lies in the incorrect importation of the 'firebase ...

What could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...