【发布时间】:2013-01-28 12:06:50
【问题描述】:
为什么在下面的例子中初始渲染的值是{{ person.name }}而不是David?你会如何解决这个问题?
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());
}
};
});
【问题讨论】:
-
我只是借用了类似于你的代码来让我的页面正常工作(我也在使用 contenteditable div 进行编辑模式)。我遇到的一个问题是我有一个部分正在使用 ng-bind-html-unsafe 而不是 ng-model ...我将如何调整您的代码以在任何一种情况下工作?
-
@KevinHoffman,这段代码不需要 ng-bind-html-unsafe,只需使用 ng-model。
标签: angularjs contenteditable angularjs-directive