What is the best approach to convert text to uppercase or lowercase based on the length of the string in Angular version 1.5?

My goal is to apply text formatting to a string named 'name'. Once the string is entered into an HTML form and the save button is clicked, the new formatted string should be displayed below the form. The formatting rule states that if the length of the string is even, it should be converted to uppercase, and if it's odd, it should be converted to lowercase.

I have implemented the logic for changing the text case inside the 'formatFactory' factory. The 'format' method within the 'formatFactory' is responsible for this task.

Here is the code from 'formattingFactory.js':

app.factory('formatFactory', function(){

var formattingFactoryObject = {};

formattingFactoryObject.format = function(name) {

    if(name.length % 2 == 0) {
        name.toUpperCase();
    } else {
        name.toLowerCase();
    }
}

});

In addition, I have a service called 'sessionService' which handles saving session data such as the 'name' and 'nickname' strings. Here is a snippet from 'sessionService.js':

angular.module('app').service('sessionService',[
'$window',
sessionService
]);

function sessionService($window) {
    this.save = save;
    this.get = get;
    this.clear = clear;

function save(key, value) {

    $window.sessionStorage.setItem(key, value);

}

function get(key, value) {
    return $window.sessionStorage.getItem(key);
}

Finally, in my controller ('sessionController.js'), I call the method for changing the string case just before saving the session data using 'vm.setServiceSession' method:

angular.module('app').controller('sessionController',[
'sessionService','formatFactory',

function sessionController(sessionService) {
    var vm = this;

    vm.getServiceSession = function() {
        // Retrieve session data here
    }

    vm.setServiceSession = function() {
        formattingFactoryObject.format(name);
        sessionService.save('name', vm.model.name);
        sessionService.save('nickname', vm.model.nickname);
        vm.getServiceSession();
    }
});

'index.html' contains the layout for the form where users can input data:

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

<!-- Include necessary stylesheets and scripts -->

<body ng-controller="sessionController as vm">
<div class="container">
    <h1>Services and Factories</h1>
    
    <!-- Form elements for name and nickname data -->
    
    <input type="button" ng-click="vm.setServiceSession()" class="btn btn-primary" value="Save"/>
    <input type="button" ng-click="vm.getServiceSession()" class="btn btn-default" value="Retrieve from Service"/>
    
    <pre>{{vm.model | json }}</pre>

</div>

Despite implementing the code, the issue persists with the text case not being changed as expected.

Answer №1

To follow @Rajesh's advice, make sure you assign the new values of name.toLowerCase() and name.toUpperCase() to a new variable name. Don't forget to return name at the end of your factory function. Also, remember to properly format the $scope.model.name before saving it in localStorage, like so:

sessionService.save('name', formatFactory.formattingFactoryObject($scope.model.name));

Your factory might also need some refactoring.

I have included a functional Fiddle for reference.

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

Having difficulty implementing a personalized color scheme for the mui component

Attempting to set the background color as midnightBlue but encountering an error: Error: Cannot read properties of undefined (reading '100') Upon reviewing the syntax, no errors were found. Perhaps this issue stems from a dependency problem? ...

Implementing dotenv in a Node JS package

I'm in the process of developing a Node application that retrieves search results through a Google Custom Search Engine (CSE). To streamline the process, I plan to extract the component responsible for sending requests to Google and receiving the res ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

Is it possible to verify if a string in JavaScript contains both numbers and special characters?

I created this function to check if a string contains numbers and special characters, but it seems to not be working correctly let validateStr = (stringToValidate) => { var pattern = /^[a-zA-Z]*$/; if (stringToValidate&& stringToValidate.leng ...

Incorporate relationships while inserting data using Sequelize

vegetable.js ... var Vegetable = sequelize.define('Vegetable', { recipeId: { allowNull: false, ... }, name: { ... }, }); Vegetable.association = models => { Vegetable.belongsTo(models.Recipe); }; ... recipe.js ... var Recipe = sequeliz ...

The useRouter hook from next/router was unable to connect because NextRouter was not activated

import { useRouter } from 'next/router'; const Navbar2 = () => { const router = useRouter(); return ( <nav className={`fixed top-0 w-full px-10 bg-white p-4 transition-all duration-500 ${isVisible ? 'top-0' : 'top-[-1 ...

Setting global variable values when a button is clicked in Javascript

My query involves JavaScript. I have an HTML template with a button (b1) that, when clicked, assigns an array to a variable called tempdata. The issue arises when trying to display this tempdata array using alert() outside the onclick function; nothing hap ...

Are there any npm modules available that can efficiently transform unstructured information into a CSV format?

In my Javascript project, I am trying to export data into a CSV file. However, I am facing an issue as the data I have may contain different headers for each row. For example, the data structure could be like this: [ { name: 'John', color: &apo ...

Vue alert: Issue encountered in data() - "TypeError: Unable to convert undefined or null to object"

Can anyone help me figure out how to remove this warning? I suspect it's because I'm trying to manipulate an undefined object. Any assistance would be greatly appreciated! Thank you! Here is the code snippet: <v-card class="ma-3 pa-3" v-for=" ...

Is there a way to identify the element causing an error in promise.map and then either log it to the console or skip it using code?

When running the code provided below, I encounter a 500 error for certain URLs in my list due to the structure of the page. The error occurs specifically on the line .map((htmlOnePage, index) => when some URLs lead to invalid pages, causing the prog ...

trigger a p:ajax event by employing a right-click action

Currently, I am utilizing JSF and Primefaces 5.2. A peculiar observation I made is that when a commandLink is used with the onclick event and p:ajax, it creates a selection effect. <h:commandLink id="commandLink"> <p:ajax event="click"/> </ ...

Encountered an issue with reading the property childnotes of null during data retrieval using ajax in PHP

Hello, I am encountering an error while trying to fetch data using ajax. The error message is "Cannot read property 'childNodes' of null". Can anyone help me identify what might be wrong with my code? I have created a form to search for data with ...

Is there a way for me to automatically generate and send a random collection each time a GET request is made on my Node.js

I have been developing a typing application that utilizes an API to fetch random quotes from . I successfully created an API using MongoDB, Node.js, and Express which functions well. However, I encountered an issue when trying to send a random collection ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

Having trouble navigating to the end of a webpage while using Python for web scraping and Spotify's web player?

I am working on a Python program that can extract a list of track names from a Spotify playlist when given the link. Here is my current progress: from bs4 import BeautifulSoup from selenium import webdriver url="https://open.spotify.com/playlist/1xXEN6Uh ...

Having difficulty extracting image and product names from Amazon or Flipkart pages using Jsoup

I'm having trouble retrieving the main image and product name from Amazon or Flipkart using Jsoup. This is my Java/Jsoup code: // For amazon Connection connection = Jsoup.connect(url).timeout(5000).maxBodySize(1024*1024*10); Document doc = connectio ...

Elevate the React experience by smoothly sliding a fixed navbar upwards when scrolling down, and elegantly sliding it

tl;dr Don't miss the solution at the end! Looking to create a slide up and down effect on a fixed navbar in react? What's the best approach - using refs or the componentDidMount lifecycle hook? hideNav = (navbar) => { const hide = () ...