Italicize word in Angular template

Is there a way to add underlines to the words "this" and "note" in the sliderNote without changing or splitting the actual text within it?

JS:

$scope.sliderNote="This is my note";

Html:

<div class="sliderNote">
      {{sliderNote}}
      </div>

css:

.sliderNote {
  font-size:12px;
  color:gray;
  text-decoration: underline;

}

Answer №1

One way to accomplish this is by developing a custom filter.

In your script, define the controller and filter as follows:

var app = angular.module('app', []);

app.controller('mainCtrl', function($scope) {
  $scope.sliderNote="This is my note";
  $scope.selectedWords = ["This","note"];
});

app.filter("underline", function($sce){
    return function(txt, phrase){
       if(phrase instanceof Array){
          if(txt === undefined){
             return;
        }
        for (var i = 0; i < phrase.length; i++) {
            var key = phrase[i];
          txt = txt.replace(new RegExp('('+key+')', 'gi'),'<span style="text-decoration: underline;">$1</span>');
        };  
       }
    return $sce.trustAsHtml(txt);
  };
});

In the view, make use of data-ng-bind-html like so:

 <!DOCTYPE html>
 <html ng-app="app">

 <head>
  <script  src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.j s"></script>
</head>

 <body ng-controller="mainCtrl">
   <div class="sliderNote" data-ng-bind-html="sliderNote | underscore :  selectedWords">

 </body>
 </html>

Check out the Plunker example here: http://plnkr.co/edit/fLSzpvWwFXQaAs5dcjBf?p=preview

Answer №2

If you want to emphasize certain words in your slideNote, one way to do it is by creating a custom filter like

{{ slideNote | underline:'this,note' }}
.

This filter takes the input from the variable slideNote, determines which words to highlight based on the parameter 'this,note', separates these words, and encloses them with <u></u> tags within the input string.

Remember to mark the output of the filter as safe to prevent HTML escaping before returning it.

For more information on filters in AngularJS, refer to the official documentation here.

Answer №3

To highlight specific words in a paragraph, use the ng-bind-html directive along with a custom function:

<div class="sliderNote" ng-bind-html="highlightWords(sliderNote)">

      </div>

JavaScript:

$scope.sliderNote="This is my note";

$scope.highlightWords = function (text){
    text.replace(" this ", " <u>this</u> ");
    text.replace(" note ", " <u>note</u> ");
    return text;
}

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

Adding Currency Symbol to Tooltip Data in Material-UI Sparklinechart

Below is a SparklineChart example using MUI library: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-charts/SparkLineCha ...

AngularJS feature enables dynamic file naming, causing JSHint error to appear

One interesting thing about my DOM with AngularJS is the following element... <img class="optional" src="assets/img/{{ctrl.optional}}.png" ng-click="ctrl.clickOptional()"> This image is dynamically generated when the page loads. Whenever I click on ...

The issue of React UseEffect not functioning properly in conjunction with firepad and firebase has been identified

When attempting to utilize the username fetched from Firebase to create a user in the FirepadUserList, the code resembles the following: import { useRef, useEffect, useState } from 'react'; import 'codemirror/lib/codemirror.css' impo ...

Image not located: 404 error in JavaScript

I am currently working with JavaScript and have encountered an issue. I have an array of objects that contain various data such as id, title, price, and image. I need to retrieve this data from the array in order to display it. While I am able to successfu ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Guide on clearing the value of the first textarea and transferring it to the second textarea using JavaScript

I have encountered an issue where the first textarea value is being copied into the second textarea because I am using the same id for the 'add more' functionality. Below is the code snippet: <div id="divShortAnswerOption_Templated"> & ...

The ng-show directive seems to be malfunctioning when used with UnderscoreJS's _.isNull function, but it functions properly when comparing

When using an ng-show directive on an element, I noticed that the UnderscoreJS helper function _.isNull behaves differently than the standard === operator. For example, when checking if newJobWorkPercentage is null: <div class="form-group" ng-show="ne ...

Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json: { "pages" : [ { "name" : "home" ...

Cycle through an array of elements and generate a fresh object

Here is an array of objects: [ {id:1,val: 5,name: 'Josh'}, {id:2,val: 7,name: 'John'}, {id:3,val: 6,name:'mike'}, {id:4,val: 7,name: 'Andy'}, {id:5,val: 8,name: 'Andrew'}, {id:6,val: 7,name: &a ...

Exploring the Logic Behind My State Store Layout - Comparing User Interface to Application State

I'm starting to get a bit confused about the difference between application state and UI state. Whenever a user picks an activity from a list on the page, an API call is triggered to retrieve the announcements for that specific activity. Is the id of ...

Steps to trigger an alert when the entered quantity exceeds the current stock levels

After developing an IMS System, I encountered a problem where my stock is going into negative figures. To resolve this issue, my primary goal is to trigger an alert whenever the quantity entered by a user exceeds the available stock. For example, if a us ...

What is the method for including an input field beside the y-axis label in Chart.js?

I'm struggling to implement a live poll using Chart.js where users can select their option by checking a checkbox next to the y-axis label. My initial attempt was unsuccessful as placing the input boxes outside of the canvas led to alignment issues wi ...

Encountered an unexpected GLTF import error in three.js due to invalid JSON syntax containing tokens like '<' and "<!DOCTYPE "

Whilst attempting to import my very first .gltf model into three.js using the Parcel bundler, I encountered a black screen and the following error message: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON a ...

Having trouble incorporating a variable into the Discord Client object in Typescript

As a newcomer to Typescript, I am working on creating a Discord bot using Typescript. I am trying to add a variable called "commands" to the Client object. In JavaScript, you can achieve this using the following code: Javascript const { Client } = require ...

Optimal banner image dimensions for responsive mobile display on various devices

What is the best way to ensure a banner image looks good on small and medium mobile devices, as well as tablets? ...

Issue with Django: Javascript not loading correctly in HTML page

Why won't my Django website load javascript files, even though the css part works fine from the same Static folder? base.html: <head> {% load static %} <meta charset="UTF-8"> <link href="{% static 'login/css/bootstrap ...

Set the side columns in CSS to have a fixed width, while the center content column should have

Check out this fiddle I created for everyone to view: http://jsfiddle.net/defaye/DhaHP/4/ For the full-screen result, click here: http://jsfiddle.net/defaye/DhaHP/4/embedded/result/ I'm encountering an issue where, after resizing the window past a ce ...

Is there a way to seamlessly incorporate a PHP tag into a Bootstrap dropdown for perfect alignment?

In relation to this query: I have successfully integrated the if/else statement into the dropdown without any issues. However, upon using the dropdown on the website, I noticed that the item generated by the if/else statement – in this case, "log in" or ...

The VBA script I use to extract data from the web is causing my laptop to run sluggishly

Today marks my first venture into creating a VBA Excel program for scraping data from a website. Initially, I attempted a simple program to scrape a single value and display it in cells(1,1). Despite encountering numerous failures and multiple warnings fro ...

Stop any accidental double clicks on the <input type="submit" /> to avoid duplicate entries

Is it possible to prevent a user from clicking twice on an input tag button with type submit? I attempted using ondblclick="javascript:void(0)", but it did not work. My code is within an Html.BeginForm, not a form element tag. Thank you in advance for al ...