Ways to assign a value to an input element in AngularJS without impacting its ngModel

JAVASCRIPT:

.directive('search', [function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            attrs.$set('placeholder', 'Word...');
            console.log(attrs);
        }
    };
}]);

Although the value attribute is being added, it isn't displayed. This issue may be related to the ngModel attribute not allowing changes to the value. However, based on what I've seen in the AngularJS documentation, it is possible to set the value programmatically. Could someone guide me on how to do this?

HTML:

<input type="text"
ng-model="query"
ng-init="inputClass='input-inactive'"
ng-class="inputClass"
ng-focus="inputClass='input-active'"
ng-blur="inputClass='input-inactive'"
ng-change="searchModelChange()"
search />

Edit: Ultimately, I want to have the input display 'Search items...' when idle, clear when focused, and revert back to 'Search items...' if empty when blurred.

I understand that achieving this functionality with an external JS function using "getElementById" may not be optimal. I believe there should be a way to accomplish this within AngularJS from the link function, but I'm unsure of how...

Edit 2: Is there a solution different from using placeholder? If I had a requirement beyond the scenario described in the first edit, how could I address it?

Answer №1

Is something along these lines what you're looking for?

.directive('search', [
  function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        var defaultText = attrs.search;

        ngModel.$render = function(value) {
          var text = (!value && value !== 0) ? defaultText : value;
          element.val(text);
        }

        element.on('focus', function() {
          if (!ngModel.$viewValue)
            element.val('');
        });

        element.on('blur', function() {
          if (!ngModel.$viewValue)
            element.val(defaultText);
        });

      }
    };
  }
]);

angular.module('app', []).directive('search', [
  function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        var defaultText = attrs.search;

        ngModel.$render = function(value) {
          var text = (!value && value !== 0) ? defaultText : value;
          element.val(text);
        }

        element.on('focus', function() {
          if (!ngModel.$viewValue)
            element.val('');
        });

        element.on('blur', function() {
          if (!ngModel.$viewValue)
            element.val(defaultText);
        });

      }
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="app">
  <input type="text" ng-model="query" search="Type here..." />{{query}}
</div>

Answer №2

The placeholder attribute is used to provide a brief hint about the expected input value in an input field (e.g. sample value, format description).

For instance,

<input type="email" id="userEmail" placeholder="Please enter your email address." class="form-control">

Is this what you are searching for?

Answer №3

To modify the placeholder text, you can utilize the onfocus and onblur attributes:

<input 
  type="text" 
  ng-model="searchUser" 
  placeholder="Search for items" 
  onfocus="this.placeholder = ''" 
  onblur="this.placeholder = 'Search for items'"
  class="form-control search-filter"
 >

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

TinyMCE - The control with the name 'content' is considered invalid and cannot receive focus

I am utilizing TinyMCE 4 and here is the code snippet for it: <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea[name=content]', ...

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

Utilizing ChartJS to convert a chart into a Base64 image within a Vue environment

I am currently utilizing the PrimeVue chart component, which is built on top of ChartJS. The configuration is very similar. The documentation indicates that I need to instantiate a new Chart() and then call toBase64Image(); My main query is, how do I ac ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

Disable system discord.js

Hey there, I'm experiencing an issue with my code and could use some help. Every time I try to use my mute command, it keeps spamming "You need permission to use command". Below is the snippet of my code: client.on('message', message => { ...

What are the best practices for implementing optional chaining in object data while using JavaScript?

In my current project, I am extracting singlePost data from Redux and converting it into an array using Object.keys method. The issue arises when the rendering process is ongoing because the singlePost data is received with a delay. As a result, the initi ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...

What are your thoughts on the practice of utilizing the useState hook within a component to send data to its parent component?

I have been working on developing an Input component that can be dynamically used in any page to store input values. The component also includes an attribute called getValue, which allows the parent component to access the input value. In my App.js file, I ...

Building module dependencies in the Dojo dojo

I'm in the process of utilizing the Dojo builder to compile a unified file that encompasses all the necessary modules for my application, excluding the application itself. Below is an illustration of a layer definition: layers: { 'dojo/dojo ...

Mastering the art of crafting and managing NodeJS promises with finesse

Currently, I am utilizing ExpressJS for handling APIs and heavily rely on promises for managing asynchronous requests such as external API calls and database queries. While this approach works well in most cases, it tends to clutter the code with numerous ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

Guide on displaying JSON information upon clicking using JavaScript

I'm having difficulty writing the logic for this code. I have extracted data from a vast API. The current code fetches all program titles (some may be repeated) and compares them with an array of late night shows, then displays them once in their own ...

Retrieve the route from a specific node in the jstree structure

Looking to retrieve the paths of selected nodes in jstree? You'll need the complete path of the nodes. I have a php file that generates the JSON, structured like this: header("Content-Type: application/json; charset=utf8"); echo json_encode(dir_to_ ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

What are the steps to transform a blob into an xlsx or csv file?

An interesting feature of the application is the ability to download files in various formats such as xlsx, csv, and dat. To implement this, I have utilized a library called fileSaver.js. While everything works smoothly for the dat/csv format, there seems ...

What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected. This is how I attempted t ...

What is the best way to reach a webpage in Protractor without using Angular?

Is there a way to navigate to a webpage without Angular using Protractor? Here is the test scenario: browser.driver.get('https://www.mysitewithlogin.com'); The outcome shows: Error message: Unable to synchronize with the page in Protractor due ...

Troubleshooting Protractor in Intellij: A step-by-step guide

While using OSX, I successfully configured an Intellij 15 run/debug task as explained in this post below: How to debug angular protractor tests in WebStorm Although the task runs fine, unfortunately, the debug feature does not work and throws the followi ...

Retrieve the HTML data and save it as page.html, displayed in a VueJS preview

After developing an innovative VueJS-based application for managing front-end content, I am now eager to enhance it with a 'download' button feature. This new functionality will allow users to easily download the previewed and edited content in H ...

Encountering a [$injector:modulerr] error while attempting to include modules in ZURB Foundation for Apps

I am currently working on a project that involves specific authentication which is functioning well in Ionic. My task now is to incorporate the same authentication system into the admin panel exclusively for web devices. I have already completed the instal ...