加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS和contentEditable双向绑定不能按预期工作

发布时间:2020-12-17 08:55:15 所属栏目:安全 来源:网络整理
导读:为什么在下面的示例中初始渲染的值是{{person.name}}而不是David?你将如何解决这个问题? Live example here HTML: body ng-controller="MyCtrl" div contenteditable="true" ng-model="person.name"{{ person.name }}/div pre ng-bind="person.name"/pre/
为什么在下面的示例中初始渲染的值是{{person.name}}而不是David?你将如何解决这个问题?

Live example here

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());
    }
  };
});
问题是,当插值尚未完成时,您正在更新视图值。

所以删除

// load init value from DOM
ctrl.$setViewValue(element.html());

或替换为

ctrl.$render();

将解决问题。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读