Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-change doesn't work on input

I'm new to AngularJS and currently struggling with the following problem.

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

The problem now is, that I can't work with this scope in a function, when adding ng-change="barFunc()" to the <input>.

How is it possible to work with ng-change or ng-watch here? It would be great if someone could make my plnkr work.

<!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>
like image 782
herrh Avatar asked Jan 20 '16 15:01

herrh


2 Answers

You have to define $scope.custom before you can access to $scope.custom.value

like image 157
Derber Alter Avatar answered Nov 15 '22 11:11

Derber Alter


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 in plunkr

like image 2
Kwarc Avatar answered Nov 15 '22 11:11

Kwarc