Ng-change does not work on input

I am new to AngularJS and currently struggling with the following issue.

As you can see here in my plnkr , I can change the value of $scope.myDate.value .

Now the problem is that I cannot work with this area in the function when adding ng-change="barFunc()" to the <input> .

How can one work with ng-change or ng-watch here? It would be great if someone could do my plnkr job.

 <!DOCTYPE html> <html ng-app="demo"> <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> <link href="//rawgithub.com/g00fy-/angular-datepicker/1.0.3/dist/index.css" rel="stylesheet"> <style> input {margin: 45px 0 15px 0;} pre{padding: 15px; text-align: left;} </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-4"> <div ng-controller="foo"> <input type="datetime" class="form-control" date-time ng-model="myDate.value" ng-change="barFunc()" format="yyyy-MM-dd hh:mm:ss" placeholder="Select datetime"> <pre>myDate: {{myDate.value}}</pre> <pre>myDate + " abc": {{ custom.value }}</pre> </div> </div> </div> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="//code.angularjs.org/1.4.8/angular.js"></script> <script src="//rawgithub.com/g00fy-/angular-datepicker/1.0.3/dist/index.js"></script> <script> angular.module('demo', ['datePicker']).controller('foo',['$scope', function($scope){ $scope.myDate = { value: '' }; $scope.barFunc = function() { $scope.custom.value = $scope.myDate.value + " abc"; }; }]); </script> </body> </html> 
+5
source share
3 answers

You must define $scope.custom before you can access $scope.custom.value

+2
source

I would use $ watch in this case:

in your controller:

 $scope.custom = { value : '' }; $scope.$watch('myDate.value', function() { $scope.barFunc(); }); $scope.barFunc = function() { $scope.custom.value = $scope.myDate.value + " abc"; }; 

or plunkr

+2
source

You can configure the observer as follows:

 $scope.$watch('myDate', function(oldValue, newValue) { $scope.barFunc(newValue); 

});

but you also need to define your custom object:

  $scope.custom = { value: '' }; 

and it should work. I do not feel that this is the best solution. I usually like it if I set up the observers because I don’t understand why something is not working as expected, then it’s better to understand why it is not working. I get what you are trying to do and offer it only as something to quickly solve your problem if you need it.

+2
source

Source: https://habr.com/ru/post/1241045/


All Articles