AngularJS和CONTENTEDITABLE双向绑定不能按预期工作 [英] AngularJS and contentEditable two way binding doesn't work as expected
本文介绍了AngularJS和CONTENTEDITABLE双向绑定不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么在下面的例子中初始呈现值 {{person.name}}
,而不是大卫
?你会如何解决这个问题?
这里活生生的例子。
HTML
<机身NG控制器=MyCtrl>
< DIV CONTENTEDITABLE =真正的NG-模式=person.name> {{person.name}}< / DIV>
< pre NG绑定=person.name>< / pre>
< /身体GT;
JS:
app.controller('MyCtrl',函数($范围){
$ scope.person = {名称:'大卫'};
});app.directive('CONTENTEDITABLE',函数(){
返回{
要求:'ngModel',
链接:功能(范围,元素,ATTRS,CTRL){
//视图 - >模型
element.bind('模糊',函数(){
范围。$应用(函数(){
。CTRL $ setViewValue(element.html());
});
}); //模型 - >视图
Ctrl键。$ =渲染功能(){
element.html(CTRL $ viewValue);
}; 从DOM //初始化负载值
。CTRL $ setViewValue(element.html());
}
};
});
解决方案
的问题是,你正在更新时,插还没有结束的观点的价值。
因此,移除
//初始化加载从DOM价值
。CTRL $ setViewValue(element.html());
或
替换它 CTRL $渲染()。
将解决这个问题。
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.
So removing
// load init value from DOM
ctrl.$setViewValue(element.html());
or replacing it with
ctrl.$render();
will resolve the issue.
这篇关于AngularJS和CONTENTEDITABLE双向绑定不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文