AngularJS and contentEditable two way binding doesn't work as expected

前端 未结 5 1650
广开言路
广开言路 2020-12-07 18:53

Why in the following example the initial rendered value is {{ person.name }} rather than David? How would you fix this?

Live example here

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 19:23

    Short answer

    You're initializing the model from the DOM using this line:

    ctrl.$setViewValue(element.html());
    

    You obviously don't need to initialize it from the DOM, since you're setting the value in the controller. Just remove this initialization line.

    Long answer (and probably to the different question)

    This is actually a known issue: https://github.com/angular/angular.js/issues/528

    See an official docs example here

    Html:

    
    
      
        
        
      
      
        
    Change me!
    Required!

    JavaScript:

    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.on('blur keyup change', function() {
              scope.$apply(read);
            });
            read(); // initialize
    
            // Write data to the model
            function read() {
              var html = element.html();
              // When we clear the content editable the browser leaves a 
    behind // If strip-br attribute is provided then we strip this out if( attrs.stripBr && html == '
    ' ) { html = ''; } ngModel.$setViewValue(html); } } }; });

    Plunkr

提交回复
热议问题