2014-04-13 24 views
3

我正在使用contenteditable角js指令。我嘗試使用ng-model訪問a標記的值,但它給出了未定義的值。contenteditable角js

這是我的HTML這裏我使用CONTENTEDITABLE指令

<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-模型我如何獲得a標記值。

+3

我建議你從幫助中刪除所有的內聯樣式(它增加了問題的噪音)。 – Nix

+0

你的例子工作正常..不知道你在做什麼錯。我注意到你使用兩個sep。變量'chatMessageName'和'secondPresonName.'該指令正確設置'chatMessageName'考慮創建一個小提琴。 – Nix

+0

http://jsfiddle.net/WHq4A/1/這是例子 – user3529681

回答

1

您正在處理範圍問題(ng-switch創建子範圍)。你需要要麼使用.$parent.

例與$parent更新NG-模型使用$parent.chatMessageName

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

例與dot/object: 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


旁註:當你發佈你的問題:包括在你的問題小提琴(未註釋),並刪除不必要的代碼,格式,因此它更具有可讀性。

+0

謝謝尼克斯。下次我會用小提琴來解釋我的問題.. – user3529681