1

I have a contenteditable div like this:

<div contenteditable="true" ng-model="name">{{ name }}</div>
<input type="button" ng-click="checkScope()" value="Click me">

In my controller:

var app = angular.module('sbAdminApp', []);
app.controller('MyCtrl', function($scope) {
    $scope.name = 'Adrian';

    $scope.checkScope = function(){
        console.log($scope.name);
    }
});

How can I get the latest value of contenteditable div using scope when I click the button?

1 Answer 1

3

you need a directive to work this

app.directive('contenteditable', [function() {
    return {
        require: '?ngModel',
        scope: {

        },
        link: function(scope, element, attrs, ctrl) {
            // view -> model (when div gets blur update the view value of the model)
            element.bind('blur', function() {
                scope.$apply(function() {
                    ctrl.$setViewValue(element.html());
                });
            });

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

            // load init value from DOM
            ctrl.$render();

            // remove the attached events to element when destroying the scope
            scope.$on('$destroy', function() {
                element.unbind('blur');
                element.unbind('paste');
                element.unbind('focus');
            });
        }
    };
}]);

and you can use it like this

<div contenteditable="true" ng-model="name">{{ name }}</div>

here is a demo

Sign up to request clarification or add additional context in comments.

4 Comments

I want to update the scope value,so how can I get current editable div scope(Like in current case "name") inside element.bind function.
directive is updating the $scope.name property
Great.I am going to wrong direction..Thanks for your last comment. +1
:) glad to help you cheerz

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.