Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html contenteditable元素中奇怪的角度数据绑定_Html_Angularjs_Contenteditable - Fatal编程技术网

Html contenteditable元素中奇怪的角度数据绑定

Html contenteditable元素中奇怪的角度数据绑定,html,angularjs,contenteditable,Html,Angularjs,Contenteditable,使用标记: <body ng-app="app" ng-controller="ctrl"> <h1>Type below in the editable div</h1> <h3>Use ng-bind:</3> <div class="editable" contenteditable=true obj="obj1" ng-bind="obj1.content"></div> <h3&g

使用标记:

<body ng-app="app" ng-controller="ctrl">
  <h1>Type below in the editable div</h1>
  <h3>Use ng-bind:</3>
  <div class="editable" contenteditable=true obj="obj1" ng-bind="obj1.content"></div>
  <h3>Content:</h3>
  <div>{{obj1.content}}</div>

  <h3>Use interpolation</h3>
  <div class="editable" contenteditable=true obj="obj2">{{obj2.content}}</div>
  <h3>Content:</h3>
  <div>{{obj2.content}}</div>
</body>
我试图编写一个带有双向数据绑定的contenteditable指令。但奇怪的事情发生了:

使用ngBind:键入类似“a”的内容,插入符号跳回第一个位置,而不是在“a”之后

使用插值:键入类似“a”的内容,它将变成“aa”

现场演示:


这里发生了什么?我如何解决它?

我用插值解决了您的问题-只需从中删除{{obj2.content}


它将正常工作。之所以会出现双符号,是因为您的指令绑定到obj2,并且在指令内部打印对象obj2。

使用初始值e.x,obj2={content:'hey'},您将看到它可以工作:。所以这不是你提到艾多克的原因,我很理解你。在您的情况下,我认为您可以使用ng模型作为指令,请参阅答案
var app = angular.module('app', []);

app.controller('ctrl', function($scope) {
  $scope.obj1 = {
    content: ''
  };
  $scope.obj2 = {
    content: ''
  };
});

app.directive('contenteditable', function() {
  return {
    scope: {
      obj: '='
    },
    restrict: 'A',
    link: function(scope, elem) {
        elem.on('keyup', function() {
          var text = elem.text();
            scope.obj.content = text;
            scope.$apply();
        });
     }
  };
});
<div class="editable" contenteditable=true obj="obj2">{{obj2.content}}</div>