How can I receive notification of changes within a template component in AngularJS 1.5?

For instance, I have a form with various input fields:

<form>
<input type="text" ng-model="$ctrl.inputText">
<input type="number" ng-model="$ctrl.inputNumber">
</form>

Since my app is component-based, I need to trigger an event in my controller whenever the data in these inputs changes. The $onChanges method only responds when the bound variable changes and does not detect changes within the template.

Answer №1

If you want to implement a change event in AngularJS, you can simply utilize the ng-change directive

var myComponent = {
  scope: {},
  bindings: {},
  controller: function() {
    this.inputText = "boo";
    this.inputNumber = 666;
    this.changeEvent = function(val) {
      console.log("change event" + val);
    }
  },
  template: [
    '<form>',
      '<input type="text" ng-model="$ctrl.inputText" ng-change="$ctrl.changeEvent($ctrl.inputText)">',
      '<input type="number" ng-model="$ctrl.inputNumber">',
    '</form>'
  ].join('')
};

angular.module('myApp', []);
angular
  .module('myApp')
  .component('myComponent', myComponent);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
    <my-component></my-component>
</div>

Answer №2

Within the Controller:


$scope.$watch("myForm.$dirty", function() {
    $scope.myForm.$setPristine();
});

HTML Form:

<form name="myForm">
    <input type="text" ng-model="$ctrl.inputText">
    <input type="number" ng-model="$ctrl.inputNumber">
</form>

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

Axios is repeatedly making GET requests to an incorrect endpoint

I have set up axios to make requests to my express backend hosted on localhost:8081 src/htpp/index.js import axios from 'axios' export default axios.create({ baseURL: 'http://localhost:8081/api/', timeout: 1000, headers: {&apos ...

Prepare for a thorough cross-referencing session

In my attempt to create a tool with 3 inputs that are interdependent - "Earn %", "Earn $" and "Own Price". Initially, the default value for "Earn percentage" is set at "10", making the initial calculation function as intended. Changing this one value auto ...

"Exploring the World Wide Web with JavaScript and Ajax in Internet

Is there a way to include a Javascript snippet at the end of some ajax content? It seems to be functioning properly in Firefox, but when I try it in Internet Explorer, the script is printed out without being executed. <script type="text/javascript"&g ...

The functionality of the bootstrap Dropdown multiple select feature is experiencing issues with the Onchange

Creating a Bootstrap Multiple Select Drop Down with dynamically retrieved options from a Database: <select size="3" name="p" id="p" class="dis_tab" multiple> <?php echo "<option>". $row['abc'] ."</option>"; //Fetching option ...

When there is no data in the request body, ExpressJS will display it as empty

A big part of my tech stack includes a website with an express server up and running. The website allows users to insert their username and password. Upon clicking the login button, the server receives a request with the username and password packed as a J ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

Should I convert to an image or utilize the canvas?

I'm debating whether it's more efficient to convert a canvas drawing into an image before inserting it into the DOM, or if it's better to simply add the canvas itself. My method involves utilizing canvas to generate the image. ...

Configuring hostname and port within next.config.js with next.js

Currently, I am utilizing next.js 9.5.x and am in search of a method to set up the hostname and port via the next.config.js file. Despite consulting the documentation, I have yet to discover a solution to this issue. Previously, I leveraged a series of .e ...

Can you explain the process of retrieving API information from a component directory with Next.js?

In the components folder, I have created a reusable component that displays user details for those who log into the system in the header section. Currently, I am attempting to utilize getInitialProps with isomorphic-unfetch. static async getInitialProps( ...

Is a loading animation needed to reload once the content is fully loaded?

Currently, I am utilizing Ionic to create a basic tab application that fetches information from an external source (specifically parse). For the most part, everything runs smoothly. However, on occasion, I encounter situations where clicking on a view rend ...

Enhancing class names in production mode with Material UI, Webpack, and React to optimize and minimize code size

webpack - v4.5+ material ui - v4.9.7 react - v16.12.1 Ordinarily, all classes should follow the pattern of the last one in the first example. However, for some unknown reason, many classes remain unchanged in production mode. Any thoughts on this issue? ...

What is the method to retrieve the return value from this ajax request?

Here's a code snippet: var information = { ObtainInfo : function() { var url = 'http://www.bungie.net/api/reach/reachapijson.svc/game/info/'+storage.get('apikey'); $.ajax({ url: url, su ...

What method is used to initialize the variables in this JavaScript snippet, and what other inquiries are posed?

As a backend developer, I'm looking to understand this JavaScript snippet. While I grasp some parts and have added comments where I am clear, there are still sections that leave me with bold questions. function transformData (output) { // QUESTIO ...

Retrieve items in Angular by sending a POST request

I am currently developing my first application using Angular and have encountered a challenge. I have the address for a POST request with an authentication token, structured like this: http://example.com/orders?authentication_token=123456 I need to imple ...

Having difficulty loading the controller into my AngularJS module

I've been attempting to organize my angularjs controllers into separate files without success. Folder Structure: --public-- --js/controller/resturant.js --js/master.js --index.php Content of master.js angular.module("rsw",[ ...

Customizing column specifications in Angular's UI-Grid

Imagine having the following dataset: let data = [ {name: 'bob', bornOn: 1510174615339}, {name: 'mary', bornOn: 1510164615339} ] When passed into a ui-grid, it results in 2 columns. To convert the epoch time to a human-readable fo ...

Can you explain the significance of the '#' symbol within the input tag?

I was reading an article about Angular 2 and came across a code snippet that uses <input type='text' #hobby>. This "#" symbol is being used to extract the value typed into the textbox without using ngModal. I am confused about what exactly ...

Guide on retrieving data from local storage and exhibiting it in an input box that is disabled using AngularJS

I have securely stored my API key in local storage. Now I need to retrieve and display that key in an input field on a different HTML page. The input field should be pre-filled with the key from local storage and disabled so it cannot be edited. Below ...

The functionality of $_GET has suddenly ceased when attempting to delete records

My web application's delete user function has suddenly stopped working, even though I haven't made any changes to it. This has left me feeling quite puzzled. I have PHP Console installed in Chrome (as well as the app), but it hasn't shown an ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...