Vladyslav Havrylenko
Vladyslav Havrylenko

Reputation: 347

AngularJS 1.5 How could I get event when something changes inside template component's

Example - I have form with some inputs like:

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

My app based on components, so in my controller I need call event when data in my inputs has been changed. Method $onChanges works only when binding var will be changed and won't affect when changes happen inside template.

Upvotes: 2

Views: 589

Answers (2)

Vladyslav Havrylenko
Vladyslav Havrylenko

Reputation: 347

In Controller:

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

    $scope.myForm.$setPristine();
 });

Html:

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

Upvotes: 0

gyc
gyc

Reputation: 4360

You can simply use ng-change

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>

Upvotes: 3

Related Questions