Why is ngModel.$setViewValue(…) not working from

后端 未结 3 1123
清歌不尽
清歌不尽 2020-12-08 02:50

I\'m writing an directive which needs an isolated scope, but I want to bind it to the parent scope via ngModel.

Here the problem is that the parent\'s scope value is

3条回答
  •  醉话见心
    2020-12-08 03:18

    I am not sure if this will work for you. However you can give it a try.

    html:

    Change me!
    Required!

    js

    angular.module('customControl', []).directive('contenteditable', function() {
        return {
            restrict : 'A', // only activate on element attribute
            require : '?ngModel', // get a hold of NgModelController
            link : function(scope, element, attrs, ngModel) {
                if (!ngModel)
                    return; // do nothing if no ng-model
                // Specify how UI should be updated
                ngModel.$render = function() {
                    element.html(ngModel.$viewValue || '');
                };
    
                // Listen for change events to enable binding
                element.bind('blur keyup change', function() {
                            scope.$apply(read);
                        });
                read(); // initialize
    
                // Write data to the model
                function read() {
                    ngModel.$setViewValue({'content': element.html()});
                }
            }
        };
    });
    

提交回复
热议问题