Use hyphens instead of spaces in angular js data binding

  <form role="form" method="POST" action="{{ url('/roles/save') }}" data-ng-app="">    
<div class="form-group">
      <label>Page-Title:</label>
       <input type="text" required value="" data-ng-model="title" name="page_title" class="form-control">                     
</div>

<div class="form-group">
 <label>Page-Alias:</label>
 <input type="text" value="@{{ title }}" name="page_alias" class="form-control">
 </div>

I am still learning Angular and experimenting with simple data-binding. I want to automatically generate an alias when a user enters the page title by replacing spaces with dashes. For example, if the user enters "Home Page," I would like the alias to be "Home-Page" or even "home-page." Below is my attempt:

 <input type="text" value="@{{title.replace(/-/g, ' ');}} name="page_alias" class="form-control">

Unfortunately, it doesn't seem to be working as intended yet.

Answer №1

"My goal is to find all the gaps and substitute them with a "-" (hyphen)"

JS

angular.module('app')
    .filter('slugify', function() {
        return function(input) {
            input = input || '';

            return input.replace(/ /g, '-').toLowerCase();
       }
    });

HTML

 <input type="text" value="@{{ title | slugify }}" name="page_alias" class="form-control">

"It would be preferable if it reads as home-page"

I included toLowerCase after the replace method for achieving this.

Answer №2

To customize your template, you have the option to create a filter:

.filter('customizeText', function() {
   return function(input) {
       return input.replace(/ /g, '-');
   }
});

Once created, you can use it like this:

 <input type="text" value="@{{ title | customizeText }}" name="page_alias" class="form-control">

Find more details here:

https://jsfiddle.net/awk4ttem/2/

Answer №3

There are two ways to achieve this: one is by using the replace within the expression, and the other is through an amazing Angular filter.

   <input type="text" value="@{{ title.replace('-',' ')}}" name="page_alias" class="form-control">

    <input type="text" value="@{{ title | replaceSpaceWithDash : '-'}}" name="page_alias" class="form-control">

app.filter("replaceSpaceWithDash", function() {
    return function(data, delimiter) {
       return data.replace(/\s/g,delimiter);
     }
   });

You have the flexibility to change the delimiter as needed in the replaceSpaceWithDash filter. Currently, I am using -, but you can modify it later according to your requirements.

To convert everything to lowercase, simply use the built-in filter | lowercase.

This will result in:

value="@{{ title | replaceSpaceWithDash : '-' | lowercase }}"

Answer №4

If you wish to trigger an action on the blur event of a textbox, you can achieve it like this:

<input type="text" required value="" data-ng-model="title" ng-blur="removeSpaces(title)" name="page_title" class="form-control">    

JavaScript:

angular.module('app', [])
.controller('myController', function($scope) {
$scope.removeSpaces = function(text) {   

   $scope.title =  text.split(' ').join('-').toLowerCase();
  }
});

Updated:

<input type="text" required value="" data-ng-model="title" ng-blur="removeSpaces(title)" name="page_title" class="form-control">  
<input type="text" value="@{{ alias }}" name="page_alias" ng-modal="alias" class="form-control">

JavaScript:

angular.module('app', [])
.controller('myController', function($scope) {
$scope.removeSpaces = function(text) {   

 $scope.alias =  text.split(' ').join('-').toLowerCase();
}
});

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

getting properties of an object using AngularJS factory

I'm facing a major roadblock with this issue. Everything is functioning well enough at the moment, but I'm struggling to retrieve the data from the factory in a non-JSON format. You can take a look at my partially functional plunker for more deta ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

In my React JS project, I am using an <Add /> component on two distinct pages. However, I am encountering an issue where only one of the pages is correctly receiving the add count prop

I could use some assistance in understanding why the logic for my counter button is not functioning properly on one specific instance. My aim is to have the count displayed by the counter look like this: https://i.sstatic.net/VdJ8o.png In order to add it ...

Looking to swap out the final value in a JavaScript array?

My task involves manipulating arrays. I start with an array of numbers called newArr. The length of this array is used to create another array filled with zeros, which I named zeroArr. const newArr = [1,3,5,8,9,3,7,13] const zeroArr = Array.from(Array(newA ...

Dynamically remove values from other fields in a React Formik form based on checkbox conditions

Currently, I am utilizing react-formik for my form implementation. I have encountered an issue with checkbox-based conditions where the checked status of a checkbox determines whether two hidden fields are displayed or hidden. If the user checks the checkb ...

Can you explain the syntax for the Javascript tag?

While browsing through some code, I stumbled upon this snippet and found myself puzzled by the not:. Is it a tag of some sort? And if so, are there alternative applications for it? var foo = { not: function(bool) { return !bool; } } I'm curious t ...

Creating a stunning 2D image from a 3D scene through the power of raytracing with webgl and three.js

My goal is to project a 3D scene onto a 2D plane using ray tracing. Although my ultimate aim is volume rendering, I am currently struggling with the basics. I have set up a three.js scene with the viewing plane attached to the camera in front of it. The S ...

What is the best way to assign multiple event handlers to Solid.js components within a single HTML element?

Introduction I am currently exploring Solid.js and facing a challenge in adding multiple event handlers to the same HTML element from different components using JSX. While it's straightforward in Vue, I have noticed that Solid.js overrides events bas ...

Populate the div with the URL parameter only when another span element is empty after a specified time interval using setTimeout

When displaying a person's name on a page, there are two different methods to consider. It can be extracted from the URL or retrieved from an email form in the CMS used. However, these two approaches sometimes conflict with each other. Currently, I h ...

Is it possible to have unique color tags in Material UI Autocomplete?

I'm currently diving into the world of material-ui and encountering some challenges that I could use help with. I am trying to incorporate multiple arrays into the autocomplete menu (e.g., options={top100Films, top100Shows}, but with the correct sy ...

When executing npm run dev, an UnhandledPromiseRejectionWarning is triggered

I'm encountering an UnhandledPromiseRejectionWarning error when running npm run dev on my Vagrant machine, and I'm struggling to identify the root cause. The console output suggests that a promise is not being properly completed with the catch() ...

React Context Matters: Troubles Unleashed

I've been facing some difficulties with passing a value from one file to another. The problem seems to be related to implementing context, but I can't seem to figure out where I went wrong! import React from 'react' const Mycontext = ...

Utilizing async await in a JavaScript event: A guide

I have coded the introduction page for my game, which includes a submit button and a textbox for users to input their username. Upon pressing the submit button, the code posts the name into a JSON file and retrieves all the data from the JSON file to sen ...

Encountered an issue while attempting to retrieve data from the HTTP URL

I encountered an issue when trying to make a request to an HTTP URL from another domain using AJAX. Every time I attempt this, I receive an error callback. DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load { ...

Designing a query feature to explore a Sequel Database utilizing a 'RETRIEVE' approach

In my index.erb, I've created a search bar with the following code: <nav> <div class="nav-wrapper"> <form> <div class="input-field"> <input id="search" type="search" placeholder="Search..." required> ...

Guide on dragging and dropping without losing the item, allowing for continuous drag and drop functionality

function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementB ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

It appears that using JQuery's .when and .done functions may result in the code executing before the script has finished loading

Since updating the hard-coded <script> with JQuery promises, I have been encountering these errors frequently: https://i.stack.imgur.com/xkWAk.png The issue seems to be inconsistent in replicating. Sometimes, the error occurs while loading the page ...

Using Node.js to convert an array into a string and then appending slashes onto it

Currently, I am in the process of learning nodeJS. Despite trying various Stack Overflow questions and answers, I have been unable to find a solution. I have been stuck on this issue for the past two days. Here is my question: Angular JS code: $scope.q ...

What is the best way to display a component based on a certain condition?

There are two instances where the Items component needs to be displayed. However, in one instance an additional component, Filters, is required while in another it is not. The Filters component is nested inside Items. When attempting to implement this, ...