What is the best way to identify when a particular character has been entered into the input field?

HTML

<div class="form-group"><label class="col-md-4 control-label" for="s1">URL</label>
                <div class="col-md-4"><input id="url" name="url" type="text" ng-change="checkVal()" ng-model="url" placeholder="" class="form-control input-md"></div>
            </div>

Javascript v1.6

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

  .controller('macroControllerAvid',['$scope', function ($scope) {
    $scope.needQuestionMark = true;
    $scope.url = '';

    $scope.checkVal = function() {
      console.log("Checking Value.");
      if ($scope.url.includes('?')) {
        console.log("Detected!");
        $scope.needQuestionMark = false;
        console.log("Question Mark Variable: " + $scope.needQuestionMark);
      } else {
        $scope.needQuestionMark = true;
        console.log("Question Mark Variable: " + $scope.needQuestionMark);
      }
    }

  }]);

The Objective

I am struggling to alter the variable needQuestionMark from the directive even though it displays correct data.

Main Aim

To identify if the URL input already has a question mark in order to prevent duplication and use an ampersand instead.

New to AngularJS, seeking guidance on the right path. Thank you!

Answer №1

It's not completely clear if I understand your question.

If you want to detect and operate on the ngModel/input value in Angular, there are different approaches you can take without using a directive.

One option is to add a $watch inside the controller:

$scope.$watch('$scope.textBox', function(newValue, oldValue) {
   // perform actions on the text when it changes
});

Another option is to use ng-change directly in the HTML:

See an ng-change example here

A third approach is to create a component, which is a new way of working with Angular similar to directives:

Learn more about Components here

Lastly, consider using controller as syntax for better organization. Here is a helpful resource to guide you:

Check out the Angular style guide

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 can we configure AngularJS UI-Bootstrap to set a minimum date of 90 days ago and a maximum date of today?

I am currently working on an AngularJS and UI-Bootstrap app that includes a datePicker with certain date restrictions. As someone new to Angular, I am seeking advice on how to set the minDate to 90 days ago and the maxDate to today's date. Check out ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

Fixing the Responsive Menu Issues

In order to achieve the desired effect of making the text from menu and logo disappear when minimizing the menu, you can use the following approach: Create a function called `smallNav()` to handle the resizing of the sidebar container: function sm ...

Utilizing Angular's DomSanitizer to safely bypass security scripts

Exploring the capabilities of Angular's bypassSecurityTrust* functions has been a recent focus of mine. My objective is to have a script tag successfully execute on the current page. However, I keep encountering issues where the content gets sanitized ...

Struggling to loop through a child in Firebase real-time database?

I'm struggling to retrieve a nested child from my database with the following structure https://i.stack.imgur.com/ZDs38.png I am attempting to get the URI from the Gallery object. When I log in, I can see this in the console https://i.stack.imgur.c ...

Ways to exit the current browser window?

Is there a way to close the current browser window using JavaScript or another language that supports this functionality? I've tried using the window.close() function, but it seems to only work for windows opened with window.open(). Thank you in adv ...

Having trouble getting my Node.js Express code to display 'Hello World' on Cloud 9 platform

Recently, I've been experimenting with Cloud 9 and have been encountering an issue while trying to execute the sample code provided on the Express website to display 'Hello World!'. I have attempted listening on various ports/IP addresses ba ...

Execute the function if the text or value begins with a certain character

I'm trying to determine whether the text within a span starts with the letter "x" and then execute a function. I've come across using "^" in strings for this purpose, but am having trouble implementing it to check the text... <span>xfoo&l ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...

Set AngularJS Material Design custom component back to its original state

I've developed a unique AngularJS custom component that acts as a wrapper for a Material Design mdSelect. It allows for easy configuration of available, default, and current values through its bindings. This component serves as an editing tool within ...

The delay in loading HTML content using FOSJsRoutingBundle and Ajax for a specific route parameter (ID)

I'm using FOSjSrouting in my symfony2.7 project. This is the code in my html.twig view: <table> <!--table header code ...etc... --> <tbody> {% for currentData in arrayData %} <tr> <td>{{ currentData. ...

Errors are thrown when utilizing hydration with RTK Query

Looking for a solution with my local API and RTK Query, I've encountered an issue when implementing server-side rendering (SSR). Here's the code snippet I'm working with: const api = createApi({ reducerPath: 'data', baseQuery: ...

Encounter error message "Angular-CLI: Karma-Webpack fails due to 'file or directory not found'"

After initially starting with the classic Angular/systemjs setup for the Tour of Heroes, I transitioned to using angular-client. The application now performs well in both development and production modes, except for when I try to run tests using ng test. A ...

Utilizing the Array object within AngularJS for a dynamic model

I have a specific way of storing my data as shown below: $scope.data = { name:'abc', Address:[{ Address1:'XXXX', state:'XXXX', County:'XXXX' }] } <input type="text" class="form-control" ...

Using Async functions with Node.js Express.js router

I've been trying to search on Google, but I can't seem to find a clear answer to this one... Is it possible to pass ES7 async functions to the Express router? For example: var express = require('express'); var app = express(); app.ge ...

Passing a custom Vue component as a property to a parent component

Struggling to find answers to my unique question, I'm attempting to create an interface where users can drag or input images using Vue. I've developed a component called Card, which combines Vue and Bulma to create card-like objects with props fo ...

What is the proper way to include a URL when submitting an AJAX form?

When I try to call a servlet using HTML, jQuery and Ajax by submitting a form, I keep getting a 404 error saying the resource cannot be found. My project is built with Maven. The Servlet is located in the src/main/java package under : com.mycompany.sample ...

Switching Languages in react-simple-keyboard: Explained

import React, { useRef, useState } from "react"; import Keyboard from "react-simple-keyboard"; import "react-simple-keyboard/build/css/index.css"; function App() { const [input, setInput] = useState(""); const [ ...

"Unlocking the Power: Sending a Complex JSON Object to PHP from the Dojo

Trying to send a complex JSON object to the server using PHP, but encountering difficulties in sending it. Here is the code snippet: Snippet from DOJO: var ObjArry=[]; var test1 = {key:value, key:value, key:value, key:value}; var test2 = {key:value, ...

What is the best way to add multiple lines of text to a webpage using the span element?

Currently, I am developing a game that involves using a map, which consists of multiple lines. My question is whether it is possible to have the span tag cover multiple lines while ensuring that each line ends with a new line character. Below is an exampl ...