Tips for retrieving the content of an input field using Angular

function HomeController($scope, navbarService) {
    var vm = this;

    $scope.showHeader = true;
    $scope.userNameNav ='';
    
    $scope.$on('toggleHeader', function(event, data) {
        $scope.showHeader = data;
    });

    $scope.$on('changeName', function(event, data) {
        $scope.userNameNav = data;
    });


    $scope.searchForItem = function() {
        console.log('search button clicked');
        console.log($scope.userSearch);

    };

}//end HomeController
.Navigation {


    width:100%;
    height:25em;
    background-image: url('http://wallpapercave.com/wp/UYnUUzz.jpg');
    background-size: cover;
background-position:50% 50%;
position: sticky;

}

.navContent {
    float:right;
}

.searchNav {

    border: 0;
    border-bottom: 1px solid red;
    outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Rental app</title>
        <link rel="stylesheet" href="styles/userPage.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="vendors/angular.min.js" charset="utf-8"></script>
        <script src="vendors/angular-route.min.js" charset="utf-8"></script>
        <script src="scripts/controllers/homeController.js" charset="utf-8"></script>
        <script src="scripts/controllers/RegisterController.js" charset="utf-8"></script>
        <script src="scripts/controllers/LoginController.js" charset="utf-8"></script>
        <script src="scripts/controllers/userController.js" charset="utf-8"></script>
        <script src="scripts/client.js" charset="utf-8"></script>
        <script src="scripts/services/credentialsService.js" charset="utf-8"></script>
        <script src="scripts/services/navBarService.js" charset="utf-8"></script>
        <script src="scripts/services/addItemSerivce.js" charset="utf-8"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js" charset="utf-8"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
        <link rel="stylesheet" href="styles/register.css">
        <link rel="stylesheet" href="styles/style.css">
    </head>
    <body ng-app='myApp'>
        <div class="" ng-controller='HomeController'>
            <div class="navImage">


            <div class="Navigation" ng-if='showHeader'>
                <div class="navContent">
                    <a href="http://localhost:7138/#!/login">Logout</a>
                    <input class='searchNav' type="button" name="button" value="Search" ng-click='searchForItem()' >
                    <input id='getUserInput' type="text"  placeholder="Search Item" ng-model='userSearch'/>{{ userSearch }}

                </div>

                <h1 class='greetUser'>Welcome {{userNameNav}}</h1>

            </div>
            </div>
            <ng-view></ng-view>
        </div>

    </body>
</html>

In the HTML document, I aim to capture the input value from the user when they click on the search button. Despite being able to log 'search button clicked' in the console, I encounter difficulty obtaining the value entered into the search box. I attempted to use vm as well but it was unsuccessful, thus I removed it.

Answer №1

Make sure to define your variable in the controller before using it in the model. For example, you can initialize it like this: $scope.formData = {}; and then access this object in both HTML and JavaScript.

Consider implementing the following version:

function CustomController($scope, dataService) {
    var vm = this;

    $scope.showHeader = true;
    $scope.userName ='';
$scope.formData = {};
    
    //Sharing information with other controllers
    $scope.$on('showHeader', function(evt, data) {
        $scope.showHeader = data;
    });

    $scope.$on('updateName', function(evt, data) {
        $scope.userName = data;
    });

    $scope.searchItem = function() {
        console.log('Button clicked');
        console.log($scope.formData.userSearch);
    };

}//end CustomController

Update your template as follows:

<input id='searchInput' type="text" placeholder="Search Item" ng-model='formData.userSearch'/>{{ formData.userSearch }}

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

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

Update gulp configuration to integrate TypeScript into the build process

In the process of updating the build system for my Angular 1.5.8 application to support Typescript development, I encountered some challenges. After a complex experience with Grunt, I simplified the build process to only use Gulp and Browserify to generat ...

Is there a way to make the delete button remove just one item from the local storage?

Is there a way to make the delete button on each item in a list remove only that specific item without deleting the others and also remove it from local storage? I have been trying to figure this out but haven't had any success so far. <div class ...

Difficulty encountered while using React.js map function to access specific JSON data

I'm encountering an issue where I am unable to read data from a JSON file. After checking that the data is stored in the component state and logging it to the console once the component is mounted, I attempted to render the URL string from the JSON da ...

Retrieve the chosen date from a DatePicker using a Javascript function

Is there a way to retrieve the user-selected date using a JS function? I attempted this method: var test = $("#datepicker").datepicker( 'getDate' ); However, when I display it with an alert, it shows [object object] instead of the date. This ...

At what point does Angular erase the $watch?

As I delve into Angular and add models to my view, I am aware that each one enters the digest loop and has a $watch function applied to it. Since Angular apps are essentially single page applications, this process is crucial for updating data across the ap ...

Require.js and R.js optimizer overlooks shimming configuration

I am facing an issue where R.js is not loading my shim properly, causing jQuery to load before tinyMCE which results in tiny being initialized before it has fully loaded. How can I resolve this problem? build-js.js: var requirejs = require('requirej ...

Ways to expand the constructor function of the THREE.Mesh class

Exploring Three.js, I'm working on creating a basic model of the solar system. My current task involves building constructor functions for planets and moons. However, I keep encountering an error message: The function setShadow() is not recognized. ...

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

Show only relevant dropdown options when a radio button is selected, and also automatically adjust options when the page

I am working on a form that includes radio buttons and a dropdown list. If the user chooses 'girls', I need to display only caroms and chess, which are specified in the girlsGames variable. If the user selects boys, I want to show the dropdown ...

Invoking the callback function within the containing scope in Typescript

I am facing an issue with my Angular component where I have a class that includes common services and functions. While passing some functions as callbacks, the scope is getting lost during execution. Let me demonstrate the problem through the code below: @ ...

Incorporate Calendly Script into your NextJs application

I'm currently working on integrating Calendly into my Next.js project. However, I am unsure about the process. My goal is to embed it on a specific page rather than in _app or _document. Here is what I have attempted so far: import Script from &apos ...

Is there a way to retrieve $httpProvider.defaults.xsrfCookieName within .factory?

Here's a question that might come from someone new to programming. I'm trying to avoid hard-coding the values for xsrfHeaderName and xsrfCookieName. Can anyone guide me on how to retrieve them from the $httpProvider? .factory('XSRFIntercept ...

Attempting to use express and nodemailer to send an email, but there is absolutely no output appearing in either the console or the terminal

When I click the send email button, it should send the data to a mailhog inbox. However, nothing happens - no errors in the console or terminal. My goal is to use nodemailer to send the name, email, chosen plan, and message from the form to the mailhog add ...

Unexpected behavior from vuelidate triggered on blur

I have implemented vuelidate for form validation. My goal is to validate user input either when they move to the next input field or click outside of the current one. <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$ ...

jQuery SlideUp and SlideDown causing Margin Bug in Internet Explorer 7

When clicking the "more info" or "less info" buttons to slide content up or down, a spacing glitch is created in IE7. Using show/hide instead of slideUp/slideDown seems to solve the issue. Is there a way to make sliding work in IE7 without causing this pro ...

When the window is scrolled to 50%, I would like to load some additional data

Looking to load data when the browser scrollbar reaches 50%... In jQuery, I created the following function: $(window).on('scroll', function () { alert("scrolling"); if ($(window).scrollTop() + $(window).innerHeight() > ...

Modify the universal variable through a jQuery action

As a newcomer to jQuery with limited experience in JavaScript, I find myself facing a dilemma. I am working on a jQuery range slider that displays two year values, and I have successfully stored both the minimum and maximum years in a variable. However, I ...

Determine the index of items within an array of objects in Lodash where a boolean property is set to true

I am new to using lodash after transitioning from C# where I occasionally used LINQ. I have discovered that lodash can be utilized for querying in a LINQ-style manner, but I'm struggling to retrieve the indexes of items in an array of objects with a b ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...