AngularJS 和 contentEditable 两种方式绑定无法按预期工作 [英] AngularJS and contentEditable two way binding doesn't work as expected
本文介绍了AngularJS 和 contentEditable 两种方式绑定无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么在下面的例子中初始渲染值是 {{ person.name }}
而不是 David
?你会如何解决这个问题?
Why in the following example the initial rendered value is {{ person.name }}
rather than David
? How would you fix this?
HTML:
<body ng-controller="MyCtrl">
<div contenteditable="true" ng-model="person.name">{{ person.name }}</div>
<pre ng-bind="person.name"></pre>
</body>
JS:
app.controller('MyCtrl', function($scope) {
$scope.person = {name: 'David'};
});
app.directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
// view -> model
element.bind('blur', function() {
scope.$apply(function() {
ctrl.$setViewValue(element.html());
});
});
// model -> view
ctrl.$render = function() {
element.html(ctrl.$viewValue);
};
// load init value from DOM
ctrl.$setViewValue(element.html());
}
};
});
推荐答案
问题是您在插值尚未完成时更新视图值.
The problem is that you are updating the view value when the interpolation is not finished yet.
所以删除
// load init value from DOM
ctrl.$setViewValue(element.html());
或替换为
ctrl.$render();
将解决问题.
这篇关于AngularJS 和 contentEditable 两种方式绑定无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文