angular.js ngModelController contenteditable指令

时间:2013-10-21 00:31:08

标签: javascript angularjs angularjs-directive

我的指令代码(为安全起见编辑了一些部分)

angular.module('myApp')
  .directive('contenteditable', function () {
    return {
      restrict: 'A',
      require: '?ngModel'
      link: function(scope, element, attrs, ngModel) {
        if(!ngModel) return;

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

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

        read(); //Init

        function read() {
            var html = element.html();
            if( attrs.stripBr && html == '<br>') {
                html = '';
            }
            ngModel.$setViewValue(html);
        }
      }
    };
  });

这应该允许我编辑表单中的字段并且它会改变,但它只会阻止表单一起

更新:

HTML代码段:

  <form class="form-group" ng-repeat="field in fields">
    <label ng-model="field">{{ field }}</label>
    <input contenteditable type="text" class="form-control" placeholder="{{field}}" ng-model="field">
</form>

0 个答案:

没有答案