ng-change not working on a text input

129,362

Solution 1

ng-change requires ng-model,

<input type="text" name="abc" class="color" ng-model="someName" ng-change="myStyle={color:'green'}">

Solution 2

I've got the same issue, my model is binding from another form, I've added ng-change and ng-model and it still doesn't work:

<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>

<ng-dropzone
  dropzone="dropzone"
  dropzone-config="dropzoneButtonCfg"
  model="pdfUrl">
</ng-dropzone>

An input #pdf-url gets data from dropzone (two ways binding), however, ng-change doesn't work in this case. $scope.$watch is a solution for me:

$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
  if (newPdfUrl !== oldPdfUrl) {
    // It's updated - Do something you want here.
  }
});

Hope this help.

Solution 3

When you want to edit something in Angular you need to insert an ngModel in your html

try this in your sample:

    <input type="text" name="abc" class="color" ng-model="myStyle.color">

You don't need to watch the change at all!

Solution 4

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Solution 5

One can also bind a function with ng-change event listener, if they need to run a bit more complex logic.

<div ng-app="myApp" ng-controller="myCtrl">      
        <input type='text' ng-model='name' ng-change='change()'>
        <br/> <span>changed {{counter}} times </span>
 </div>

...

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
      $scope.name = 'Australia';
      $scope.counter = 0;
      $scope.change = function() {
        $scope.counter++;
      };
});

https://jsfiddle.net/as0nyre3/1/

Share:
129,362
Ashwin
Author by

Ashwin

Updated on July 09, 2022

Comments

  • Ashwin
    Ashwin almost 2 years

    I am new to angular js. In my code there is color picker initialized from a text field. User changes the value of color and I want that color to be reflected as a background of a text in a span. It is not working. What is missing?

    HTML:

    <body ng-app="">
       <input type="button" value="set color" ng-click="myStyle={color:'red'}">
       <input type="button" value="clear" ng-click="myStyle={}">
       <input type="text" name="abc" class="color" ng-change="myStyle={color:'green'}">
       <br/>
       <span ng-style="myStyle">Sample Text</span>
       <pre>myStyle={{myStyle}}</pre>
    </body>
    

    Plunker - http://plnkr.co/edit/APrl9Y98Em0d6rxuzRDE?p=preview

    However when I change it to ng-click it works.