2

To be able to watch the contents change for a contenteditable div or an input element, I have created the following directive:

app.directive('contenteditable',function() { return {
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
        // view -> model
        element.bind('input', function() {
            scope.$apply(function() {
                ctrl.$setViewValue(element["0"].tagName=="INPUT" ? element.val() : element.text());
                scope.watchCallback(element.attr('data-ng-model'));
            });
          });
        // model -> view
        ctrl.$render = function() {
            element.text(ctrl.$viewValue);
            element.val(ctrl.$viewValue);
        };
     }};
});

My Test Controller looks like:

function TestController($scope) {
    $scope.singleVal = "X";
    $scope.multiVal = ["A"];
    $scope.addRow = function() {
        $scope.multiVal.push("");
    };
    $scope.watchCallback = function(modelName) {
        console.log(modelName+" was changed");
    }; 
}

When I test it against the following html, the singleVal (statically created) behaves well, but my multiVal (dynamically created using ng-repeat) doesnt. When I input a value, it just retains the original value (i.e the model is not getting refreshed). Please help.

<div data-ng-controller="TestController">
    <div contenteditable="true" data-ng-model="singleVal"></div>
    <button data-ng-click="addRow()">Add Row</button>
    <table data-ng-repeat="val in multiVal"><tr><td>
        <div contenteditable="true" data-ng-model="val"></div>
    </td></tr></table>
</div>

1 Answer 1

3

You can't bind ngModel directly to a string in an array. You'll need to store an array of objects inside of multiVal:

$scope.multiVal = [{property: "A"}];

Demonstrated here: http://jsfiddle.net/YMJzN/

Btw, you'll also want to adjust $scope.addRow to do the same...

$scope.addRow = function() {
    $scope.multiVal.push({property:'new'});
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.