0

everyone. I have a trouble with angularjs. I created custom directive for input[type="text"] and passed into variable as model. But ng-change event called function with previous value of variable. Example: State: 0, Type 1, In function - 0. State: 1, Type 548, In function - 1. State:548, Type 3, In function 548.

My html:

<div ng-controller="simpleCTRL">

<mr-textfield is-required="true" value="val" title="Minutes" type="text" change="ChangeVal()"></mr-textfield>
<input type="text" ng-model="val" ng-change="ChangeVal()"/>

</div>

</div>

And js:

<!-- language: lang-js -->    
angular.module('SimpleInterestApp', [])
  .controller('simpleCTRL', function($scope) {

  $scope.val = 0;

    $scope.ChangeVal = function() {
      console.log($scope.val);
    };


  })
  .directive('mrTextfield', function () {
    return {
        restrict: 'E',
        template: "<div class='textfield'><input type='{{::type}}' ng-required='isRequired' ng-model='value' ng-change='change()'><span class='bar'></span><label>{{::title}}</label></div>",
        replace: true,
        transclude: true,
        scope: {
            value:"=",
            title:"@",
            type:"@",
            isRequired:"=",
            change:"&"
        }
    };
});
Midas74
  • 13
  • 3

1 Answers1

0

Wrap console.log inside a $timeout.

$scope.ChangeVal = function() {
  $timeout(function() {
    console.log($scope.val);
  })
};

See working plunker.

lzagkaretos
  • 2,842
  • 2
  • 16
  • 26
  • Well, it's work for me! Thanks you! But... why? Where is magic? It's hack, isn't? – Midas74 Dec 21 '17 at 11:50
  • $timeout is not a hack. If you plan to learn AngluarJS stuff, you should definately read about angular digest cycles etc. Taken from [here](https://www.codingeek.com/angularjs/angular-js-apply-timeout-digest-evalasync/) "$timeout tells Angular that after the current cycle, there is a timeout waiting and this way it ensures that there will not any collisions between digest cycles and thus output of $timeout will execute on a new $digest cycle." – lzagkaretos Dec 21 '17 at 11:54
  • Thanks again! I think $timeout it's just wrapper of standart JS setTimeout – Midas74 Dec 21 '17 at 11:58