I am creating an angular directive that wraps html input using a group of bootstrap forms. I use the ng-change event to listen for changes, but I get the old value inside the ng-change handler. To show this, I created the same directives, one uses ng-keyup, and the other uses the ng-change event to listen for changes.
var app = angular.module('app', []);
app.controller('home', function() {
this.textKeyUp = 'KeyUp';
this.textNgChange = 'NgChange';
this.textKeyUpChanged = function() {
console.log('Changed on KeyUp:', this.textKeyUp);
};
this.textNgChangeChanged = function() {
console.log('Changed on NgChange:', this.textNgChange);
};
});
app.directive('apTextKeyUp', function() {
return {
controller: function() {},
controllerAs: 'ctrl',
bindToController: {
model: '=',
change: '&'
},
scope: {},
template: '<input ng-model="ctrl.model" ng-keyup="ctrl.change()" />'
};
});
app.directive('apTextNgChange', function() {
return {
controller: function() {},
controllerAs: 'ctrl',
bindToController: {
model: '=',
change: '&'
},
scope: {},
template: '<input ng-model="ctrl.model" ng-change="ctrl.change()" />'
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body ng-controller="home as ctrl">
<h3>KeyUp</h3>
<ap-text-key-up model="ctrl.textKeyUp" change="ctrl.textKeyUpChanged()"></ap-text-key-up>
<h3>NgChange</h3>
<ap-text-ng-change model="ctrl.textNgChange" change="ctrl.textNgChangeChanged()"></ap-text-ng-change>
</body>
</html>
Run codeBoth directives update the model value, but inside the textNgChangeChanged handler value has not yet been updated.
Is it for design? How can I fix this problem?
source
share