简体   繁体   中英

How to prevent default attribute values with angular directive

I have an angular directive which allows content editable divs to work with ng-model. Looks like this

app.directive("contenteditable", function() {
return {
  restrict: "A",
  require: "ngModel",
  link: function(scope, element, attrs, ngModel) {

    function read() {
      ngModel.$setViewValue(element.html());
    }

    ngModel.$render = function() {
      element.html(ngModel.$viewValue || "");
    };

    element.bind("blur keyup change", function() {
      scope.$apply(read);
    });
   }
};
});

however, whenever I use it with <div contenteditable="false"></div> to initialize to false, it still defaults to true. My goal is to have blocks of text that I can toggle between editable and uneditable, but am not sure how to override this default behavior without getting hacky.

Have you tried passing in the boolean via scope

app.directive("contenteditable", function() {
    return {
        restrict: "A",
        require: "ngModel",
        scope: {
            disabled: @disabled
        }
        link: function(scope, element, attrs, ngModel) {

           // reference scope.disabled to access attribute
       }
   };
});

Then set the disabled property in your HTML element like this.

<div contenteditable disabled="false"></div>

I figured it out: it was a configuration error. Long explanation, but the directive had nothing to do with the issue, as I didn't even attach it to the controller properly. I'm using ServiceNow and so angular configuration works a little differently. I believe that ng-model forced the contenteditable property to be true when I explicitly specified it (even if i specified it as false). If I didn't specify a value for contenteditable, then ng-model would not work at all, even if I changed contenteditable to be true dynamically. I renamed the directive ngContenteditable, actually attached it to controller, and toggle the regular contenteditable attribute and it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM