Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way binding of contenteditable item inside ng-list

I am looking to update Phone Name in a list of phones using contenteditable attribute. I have tried using ng-change but thats not getting fired. Is there any way I can do this?

I have a list of Store.Phones

<ul class="store">
  <li ng-repeat="Phone in Store.Phones">
     <strong contenteditable> {{Phone.Name}}</strong>
  </li>
<ul>

So now when I edit Phone name I need to get it updated in the list.

I have tried something like this with model pointing to the element. This is not working.

<strong ng-model='Store.Phones[$index].Name'> {{Phone.Name}}</strong>

Also

<strong ng-model='PhoneName' ng-change='PhoneNameChanged()'> {{Phone.Name}}</strong>

but in this case the method is not getting fired.

like image 725
Phani Avatar asked Feb 27 '13 09:02

Phani


1 Answers

Edit

Here's an example based on the example in the Angular docs which just uses ng-repeat. Since ng-repeat creates a new scope for each iteration, it shouldn't be a problem.

<!doctype html>
<html ng-app="form-example2">
<head>
    <script src="http://code.angularjs.org/1.0.5/angular.min.js"></script>
    <script>
    angular.module('form-example2', []).directive('contenteditable', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                // view -> model
                elm.bind('blur', function() {
                    scope.$apply(function() {
                        ctrl.$setViewValue(elm.html());
                    });
                });

                // model -> view
                ctrl.$render = function() {
                    elm.html(ctrl.$viewValue);
                };

                // load init value from DOM
                ctrl.$setViewValue(elm.html());
            }
        };
    });
    </script>
</head>
<body>
    <div ng-repeat="i in [1, 2, 3]">
        <div contentEditable="true" ng-model="content" title="Click to edit">Some</div>
        <pre>model = {{content}}</pre>
    </div>
    <style type="text/css">
    div[contentEditable] {
        cursor: pointer;
        background-color: #D0D0D0;
    }
    </style>
</body>
</html>

Original

There's an example of how you can do just that here: http://docs.angularjs.org/guide/forms

It's under the "Implementing custom form controls (using ngModel)" header.

like image 108
Anders Ekdahl Avatar answered Oct 19 '22 20:10

Anders Ekdahl