【发布时间】:2016-01-13 19:21:01
【问题描述】:
我正在创建 angular 指令,它使用引导表单组包装 html 输入。我使用 ng-change 事件来监听更改,但我在 ng-change 处理程序中获得了旧值。为了显示这一点,我创建了相同的指令,一个使用 ng-keyup,另一个使用 ng-change 事件来监听更改。
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>
两个指令都更新模型值,但内部 textNgChangeChanged 处理程序值尚未更新。
这是设计使然吗?我该如何解决这个问题?
【问题讨论】:
-
你认为你可以提供这个实现的 jsfiddle 或 plunkr 吗?