Fixing Selected Button State & Styling in ServiceNow AngularJS Component
Looks like you’re really close to getting this working—let’s break down the issue and fix it step by step.
First, I spot a variable mismatch in your code that’s almost certainly causing the selected state to not trigger correctly. Let’s look at your snippet:
1. Fix Variable Consistency Your ng-repeat is iterating over time items, but your ng-class check uses slot.apptTime—that’s a typo! Plus, your ng-click sets selectedSlot = time, but you’re comparing against slot which doesn’t exist in this scope. Let’s standardize the variable name (I’ll use slot for clarity, but you can stick with time if you prefer):
<div class="chiclets">
<button
class="btn btn-slots"
ng-class="{'btn-selected': c.selectedSlot.apptTime == slot.apptTime }"
ng-click="c.selectedSlot = slot"
ng-repeat="slot in c.availableSlots">
{{ slot.apptTime }} <!-- Display the time value here -->
</button>
</div>
Key fixes here:
Aligned ng-repeat variable name with the ng-class comparison (uses slot everywhere) Added c. prefix to selectedSlot to ensure it’s bound to your component’s scope (critical in ServiceNow to avoid scope inheritance bugs) Updated ng-click to store the full slot object in c.selectedSlot, making the state comparison reliable 2. Initialize the Selected State in Your Client Script Make sure you initialize c.selectedSlot in your component’s client script so Angular has a baseline to compare against. For example:
function() {
var c = this;
// Initialize empty selected slot (or set a default selected slot if needed)
c.selectedSlot = {};
// Replace with your actual available slots data source
c.availableSlots = [
{ apptTime: "9:00 AM" },
{ apptTime: "10:00 AM" },
{ apptTime: "11:00 AM" }
];
}
3. Add Your Selected State CSS Define the .btn-selected class in your component’s CSS section (or a linked stylesheet) to style the active button:
.btn-slots {
/* Base button styles */
padding: 8px 16px;
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
margin: 0 4px 8px 0;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-selected {
/* Selected state styles */
background-color: #007bff;
border-color: #0056b3;
color: #fff;
font-weight: 600;
}
4. Verify the State is Working To confirm the selected state is functioning:
Inspect the button element in your browser’s dev tools—clicking a button should add the btn-selected class Log console.log(c.selectedSlot) in your client script to confirm the object updates when you click a slot 内容的提问来源于stack exchange,提问作者Dave