简体   繁体   中英

How to get the content out of an editable div in angularjs

I am trying to get the content out of an editable div. But i am stuck at implementing the angular template for it.

I am not sure how to map model data from html template to angular controller.

<div ng-repeat="todo in todos">                 
    <div class="todo.id" ng-model={{ ? }} contenteditable="true">
        <pre>{{ todo.text }}</pre>                          
    </div>
    <button type="button" class="btn btn-link"
        ng-click="editTodo(todo.id)">Edit</button>
</div>

I want to pass whatever text i have under

<div class="todo.id"></div> 

Since my div is under ng-repeat, i cannot set ng-model to one scope variable.

What should i have within "ng-model={{ ? }}". Or is there a workaround for such a scenario.

Please guide me on this.

To make a div content editable in angular, you need to create a contenteditable directive.

There is an example for this in the angular documentation here:

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#custom-control-example

and a great blog entry from Gabo Esquivel on the topic here: http://gaboesquivel.com/blog/2014/in-place-editing-with-contenteditable-and-angularjs/

As you can see in Gabriel's example, the code for such a directive would be like this (I've added some comments to better understand whats going on):

app.directive("contenteditable", function() {
  return {
    require: "ngModel",
    link: function(scope, element, attrs, ngModel) {

      //read the text typed in the div (syncing model with the view)
      function read() {
        ngModel.$setViewValue(element.html());
      }

      //render the data now in your model into your view
      //$render is invoked when the modelvalue differs from the viewvalue
      //see documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#
      ngModel.$render = function() {
        element.html(ngModel.$viewValue || "");
      };

      //do this whenever someone starts typing
      element.bind("blur keyup change", function() {
        scope.$apply(read);
      });
    }
  };
});

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM