angularjs - Angular js中的内容可编辑

标签 angularjs angularjs-directive angular-ngmodel

我正在使用 Angular js 的 contenteditable 指令。我尝试使用 ng-model 访问 a 标签的值。但它给出了未定义的值。

这是我使用 contenteditable 指令的 html

<span ng-switch on="editgroupChatFieldFlag" style="width: 87%;margin-right: 0;float:left;"  ng-hide="displatSessionTitleFlag==false">   
    <h5 style="float:left;margin: 7px 14px 0;margin-right: 0;">Chat Session : </h5>
    <a ng-switch-when="true" contenteditable="true" strip-br="true" ng-model="chatMessageName" style="margin-right: 0;width: 59%;margin-left: 4px;" ng-keydown="changeNameFunc($event)">{{secondPresonName}}</a>
    <a ng-switch-when="false" style="margin-right: 0;width: 59%;margin-left: 4px;">{{secondPresonName}}</a>         
</span>

和这个 contenteditable 指令

app.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 <br> behind
          // If strip-br attribute is provided then we strip this out
          if( attrs.stripBr && html == '<br>' ) {
            html = '';
          }
          ngModel.$setViewValue(html);
        }
      }
    };
  });

谁能告诉我如何使用 ng-model 获取 a 标签值。

最佳答案

您正在处理范围问题(ng-switch 创建了一个子范围)。您需要使用 .$parent.

使用 $parent 更新 ng-model 以使用 $parent.chatMessageName 的示例:

<a ng-switch-default contenteditable="true" 
   strip-br="true" 
   ng-model="$parent.chatMessageName" >Enter</a>

点/对象示例: JS

--controller
$scope.myType = {
    chatMessageName: ''
};

HTML:

<!-- html -->
<a ng-switch-default 
   contenteditable="true" 
   strip-br="true" 
   ng-model="myType.chatMessageName" >Enter</a>
<a>{{"Text "+ myType.chatMessageName}}</a> 

自学:https://github.com/angular/angular.js/wiki/Understanding-Scopes


旁注:当您发布问题时:在您的问题中包含 fiddle (不是评论)并删除不必要的代码,并设置格式以使其更具可读性。

关于angularjs - Angular js中的内容可编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23047093/

相关文章:

angularjs - Angular 2 : Trouble with Custom Components

JavaScript 正则表达式 三元字符串

javascript - 从 JS 外部访问 Angular 对象的函数

javascript - 让 Gojs FlowCart 在 AngularJS 上工作

angularjs - ng-repeat 和 ng-controller 在同一个 DOM 元素上

javascript - 如何将我的子对象推送到数组?

javascript - array.splice 在 Angular Js 指令中显示奇怪的行为

javascript - ngModelOptions 在指令中不起作用

javascript - 如何*ngFor 超过一组 ngModel 可绑定(bind)属性