Sara Sara - 1 month ago 7
HTML Question

Angularjs: how to update value of table based on user input?

Here is my code:

<tbody>
<tr ng-repeat="list in results">
<td>{{list.name}}</td>
<td contenteditable>{{list.phone}}</td>....
<button class="btn" type="button" style="" ng-click="update(results)">
Update Data
</button>


User can change the phone number when he hits the
Update Data
button the value of phone for that record should be the new user typed value.
How can I update the results records based on user input?

Answer Source

Create your own contenteditable directive that overrides the basic one. Here is how I have seen it done. The basic idea is that you set the ng-model attribute to be bound to the elements inner html. Then anytime the editable content changes, the html is updated and a digest cycle is fired. It utilizes the Angular ngModel controller.

HTML

<div contenteditable="true" ng-model="list.phone"></div>

Directive

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

      element.bind('blur change', function() {
        scope.$apply(function() {
          ngModel.$setViewValue(element.html());
        }); 
      });

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