Capturing the value of an input field within a controller in AngularJS

I have been programming with JSP and Angular JS. Currently, I am faced with a scenario where I need to work with a JSP page containing a hidden input field. To set the value of this input field, I am using a session attribute like so:

  String policy = (String)session.getAttribute("POLICY_CHANGE");

  <input type="hidden" value="<%=policy%>" name="policy" ng-model="$scope.policyChange" />

My main challenge is how to bind the value of this input field to a variable $scope.policy within my controller.

JS

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.policyChange= ; // My goal is to assign the input field's value here.
});

Answer №1

If you want to set the ng-model directive for your input, here is how you can do it:

 <input type="hidden" value="<%=policy%>" name="ng2_session" ng-modal="vm.policyChange" ng-model="policy" ng-init="policy='<%=policy%>'" />

In the controller, make sure to use the watch method.

The $watch function allows you to monitor changes within the $scope

Here's a JavaScript example:

 app.controller('myCtrl', function($scope) {
   console.log($scope.policy); // This will display the input field value.
 });

For a simple illustration:

function MyCtrl($scope) {
   $scope.$watch('policy', function() {
      console.log($scope.policy);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="MyCtrl">
      <input type="text" ng-model="policy" ng-init="policy='Bob'"/>
  </div>
</div>

Important Note: The watch method is particularly useful when you need to execute certain code upon a change in the $scope.variable.

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

Arrange a set of items using AngularJS according to specific criteria

Hello, I'm new to Angular I've created an angular app and you can view it in this plunkr. Can someone guide me on how to sort the list displayed here using angular? I want the course with the flag to always stay on top, while sorting the rest o ...

Tips for creating a personalized dialog box after logging in with React Admin based on the server's response

One of my requirements is to allow users to select a role during the login process. Once the user enters their username and password, the server will respond with the list of available roles. How can I implement a dialog where the user can choose a role fr ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

Modifying the Position of the Search Box within DataTables by Manipulating DOM Elements

As a newcomer to the jQuery datatables plugin, I am still learning how to use it effectively. I have connected the plugin to my tables using the following code: $(document).ready(function() $('#table_id').dataTable({ }); }); ...

What is the way to activate Dynamic ng-model from a controller?

I am implementing a loop in my HTML code where each iteration dynamically creates a model. Here is an example of how the loop looks: <tr ng-repeat="item in voucherItems"> <td><input type="text" ng-model="this['id-' + $index ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Element was removed upon clicking only once

Can anyone help me figure out why the behavior of .remove() with $postNav.remove(); is different here? When you click on "I'm a tag" for the first time, both the <li> and <ol> are deleted as expected. However, on the second click, only the ...

Error: The requested collection# cannot be found in the Node.js Express routing system

Recently, I have started learning nodejs and implemented a simple API that allows users to log in with passport and then redirects them to the /collections route. While this part is functioning correctly, I am encountering issues with POST requests which a ...

How can two unique links toggle the visibility of divs with two specific IDs?

I am developing an interactive questionnaire that functions like a 'create your own adventure' story. The questions are shown or hidden depending on the user's responses. Below is the HTML code: <!-- TIER 3 ============================== ...

Is there a way to prevent the letters from moving when I hover over them?

What occurs when the numbers are hovered over: https://gyazo.com/20b6426d435551c5ee238241d3f96b4d Whenever I hover over the pagination numbers, they shift to the right, and I am unsure of what mistake I made in my code that's causing this. Below, I ...

Incorrect pagination handling using AngularJS bootstrap

HTML Code <body ng-app="MyApp"> <div ng-controller="PaginationCtrl"> <table class="table table-striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th& ...

What is the best way to restructure this deeply nested JSON information?

I'm working with the payload structure of my API and I want to format the data in a way that allows for dynamic display on the frontend without hardcoding column names. Currently, I am using DRF, axios, and react-redux, but I feel like I may need to d ...

AngularJS $http.get request not working as expected

Hi there, I'm currently facing an issue with retrieving data from a webpage for use on my own website. I'm working with AngularJS and attempting to fetch data from . When checking my page in Chrome, I encountered the following error: Refere ...

Using v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router. The following code is functioning correctly: export default async function Page() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); ...

No acknowledgment from command

Why doesn't the bot respond when I run this command? There are no errors. Do I have the role that matches in r.id? client.on('message', async message => { // Check if the user has a role with an id if(message.author.bot) return; ...

Securing Your ExpressJs API Files from Prying Eyes in Developer Tools

Typically, when I utilize developer tools in Google and choose to open an API file in a new tab, I am able to view the data as illustrated below. However, there are occasions where upon attempting the same action on certain websites, a security precaution ...

Unable to locate 'react' for mdl module

Currently working on my first website using react, following a tutorial available at this link I am attempting to install and utilize the material lite module, but encounter a compilation error when starting npm with the following message: Error: Module ...

The inner workings of v8's fast object storage method

After exploring the answer to whether v8 rehashes when an object grows, I am intrigued by how v8 manages to store "fast" objects. According to the response: Fast mode for property access is significantly faster, but it requires knowledge of the object&ap ...

Discovering the technique for accessing the parent component in AngularJS 1.5

Hey there, I'm currently working on displaying simple components in AngularJS where the child component needs to access the parent's name. Here is a snippet of my code: Here is my HTML file: <html> <head> <script type='t ...