Question

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?

Was it helpful?

Solution

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);
      };
    }
  }
});

OTHER TIPS

I added below code to my directive in Zack's answer and it works.

scope: {
eventHandler: '&ngClick'
},

Try this code, It's just like a key...

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

and

Js Code

var xxx = [];
        $scope.results = xxx;
        if ($scope.results.length == 0) {
            $scope.results = [{ name: "ramesh", phone: "123" }, { name: "ramesh1", phone: "1231" }, { name: "ramesh2", phone: "1232" }, { name: "ramesh3", phone: "1233" }];
        }
        $scope.update = function (index) {
            $scope.results[index.$index].phone =  "100";
            $scope.$apply();
            xxx = $scope.results;
        }

See : http://jsfiddle.net/d8CD9/4/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top