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

JQuery Chosen extension - Go back to "Choose an option"

This is a select element with the Chosen plugin applied to it: <label class="radio-inline"><input type="radio" name="reset" value="reset">Reset</label> <select id="listclient"> <option value=""></option> <option val ...

Error in jQuery when element is not found

On my website, I use multiple jQuery functions, but not all of them are necessary on every page. These functions are all located in one XXX.js file, such as: jQuery(function() { $(".title").slug({ slug:'slug', hide: false }); }); ...

Why does the code require the use of window when the Javascript error object is not functioning properly?

I'm struggling to grasp the distinction between var maxResult = window.max(maxValInt1, maxValInt2); which functions properly, and var maxResult = max(maxValInt1, maxValInt2); which gives an error "object is not a function". Why do I have to inclu ...

Issue of displaying buttons based on sibling's height under certain conditions

OBJECTIVE I have undertaken a project to enhance my skills in React and TypeScript by developing a UI chat interface. The design requirement is that when a chat message has enough vertical space, its action buttons should appear stacked vertically to the ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

Steps to eliminate pre-chosen alternatives upon loading select control?

When using react-select with pre-selected options and multiple select enabled, the issue arises where clicking on the Select box still displays the already pre-selected options. How can I remove these duplicate options from the list? Below is a snippet of ...

Is it possible to create an AngularJS and jQuery Calendar Directive that activates by clicking on a Bootstrap glyphicon?

I have successfully created a directive for my calendar using AngularJS and jQuery. The datepicker pops up when the user selects the input box. Now, I am attempting to allow the user to click on Bootstrap's 'glyphicon glyphicon-calendar' to ...

AngularJS Circular Dependency - Metamorphosis

Seeking advice on dealing with nested resources in an API. I am creating "transformers" to format data for better usability. However, I am facing a circular dependency issue due to the nature of nested resources and bidirectional relationships. For examp ...

Is it possible for me to ensure that the argument passed to `res.write` is sent as one solid chunk?

When utilizing express' res.write method to send chunks back to the requestor, it is important to note that one call to res.write does not necessarily mean the argument passed will be received as a single chunk. This can complicate the process of pars ...

RxJS - Only emit if another source does not emit within a specified time frame

Imagine having two observables. Whenever the first one emits, there should be a 2-second pause to check if the other observable emits something within that timeframe. If it does, then no emission should occur. However, if it doesn't emit anything, the ...

Styled-components is not recognizing the prop `isActive` on a DOM element in React

In my code, I have an svg component that accepts props like so: import React from 'react'; export default (props) => ( <svg {...props}> <path d="M11.5 16.45l6.364-6.364" fillRule="evenodd" /> </svg> ) ...

"After the document is fully loaded, the Ajax post function is failing to work

I am looking to trigger an Ajax call once my document has finished loading. Here is the code I currently have: <script> $(window).bind("load", function () { getCategories(); }); </script> <script> ...

Moment JS initialization and the utc() function

I am trying to comprehend the way Moment JS initializes its moment object. For instance, let's say I want to create a moment for the date and time: April 1, 2000, 3:25:00 AM with a UTC offset of +8 hours from UTC/GMT. To represent this in JavaScript ...

React JS - In order to display multiple children, consider utilizing an array rather than individual elements

Currently, I am employing React for my application and utilizing an API located at http://localhost:8080/api/suppliers/supplier/list to fetch data. Upon inspecting the Google Chrome console, this is the format of the data structure I am receiving: 0:{ ...

Issue with Angular js Factory calling as "function is not defined"

I am currently working on adding an auto-completion field using the Typeahead directive. When I follow the example provided at http://angular-ui.github.io/bootstrap/#/typeahead it works perfectly fine. However, I am facing difficulties when trying to enca ...

What is the best way to create an array in jQuery based on the presence of set variables?

Currently, I am working with 5 different variables in my project: var item_id var status var next_contact var email var phone_number var comment These variables are being sent to my server via a POST request enclosed in an array: data = {'item_id&a ...

Exploring the capability of utilizing undefined properties within the ng model in Angular

Received a code and noticed that the properties like user.name or user.email are being used in ng-model without being declared in the controller. How is it still functioning? How can we send user information to the controller function using ng-click="upda ...

Use JavaScript to convert only the initial letter to uppercase

Once again, I am in the process of learning! Apologies for the simple questions, but learning is key... Attempting to implement a trick I found online to change all letters to uppercase, I am now trying to adjust it to only capitalize the first letters. T ...

Designing a unique shape geometry using THREE JS

I've been struggling to replicate an existing city in a 3D environment using THREE.js. I have coordinates for approximately 1000 buildings, each with a varying number of corners making it impossible to use standard cubeGeometry. I attempted to create ...

Remove array element by key (not numerical index but string key)

Here is a JavaScript array that I am working with: [#ad: Array[0]] #ad: Array[0] #image_upload: Array[0] 13b7afb8b11644e17569bd2efb571b10: "This is an error" 69553926a7783c27f7c18eff55cbd429: "Yet another error" ...