点击添加内容可编辑div

时间:2017-11-06 12:13:15

标签: angularjs angularjs-directive

我想在点击按钮时添加内容可编辑div。到目前为止,在线资源说我必须为此创建一个指令。我试过了。以下代码无效

app..directive("addEditableDiv", function($compile){   
  return{
    restrict: 'A',
    require: "ngModel",
    link: function(scope , element){        
       element.bind("click", function(e){

      var childNode = $compile('<div ng-click="addDiv()" > here</div>')(scope)
      element.parent().append(childNode);

       });

        scope.addDiv = function(scope , element , attrs , ngModel){

                function read() {
                  ngModel.$setViewValue(element.html());
                  ngModel.$render = function(){
                    element.html(ngModel.$viewValue || "");
                  };

                  element.bind("click to write", function(){
                    scope.$apply(read);
                  })

                }
              }
    }
}
})

1 个答案:

答案 0 :(得分:1)

以下是内容可编辑div的工作代码:(您也可以使用库来实现此功能)

var app = angular.module("MyApp", [])
  .controller('Controller', function($scope) {
    $scope.totalEditableDiv = [];
    $scope.addDiv = function() {
      $scope.totalEditableDiv.push($scope.totalEditableDiv.length);
    }
    $scope.addDiv();
  })
app.directive("contenteditable", function() {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attrs, ngModel) {

      function read() {
        ngModel.$setViewValue(element.html());
      }

      ngModel.$render = function() {
        element.html(ngModel.$viewValue || "");
      };

      element.bind("blur keyup change", function() {
        scope.$apply(read);
      });
    }
  };
});
[contenteditable] {
  border: 2px dotted #ccc;
  background-color: #eee;
  padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="MyApp">
  <div ng-controller="Controller">

    <div ng-repeat="editableDiv in totalEditableDiv">
      <div contenteditable ng-model="text[$index]"></div>
      <br>

      <b>Source of the Div:</b>
      <p style="border:1px solid green;padding:15px;">{{text[$index]}}</p>
    </div>
    <button ng-click="addDiv()" style="color:blue">Add More</button>
  </div>
</body>