如何从ACE-Angular编辑器中获取值

时间:2015-01-30 17:17:23

标签: angularjs

我在代码编辑器上输入的任何内容都无法获得Ace代码编辑器结果。

如您所见,我设置了具有所有功能的控制器 和选项。唯一不起作用的是从编辑器渲染结果。提前谢谢....

app.controller('AceCtrl', function ($scope) {

      $scope.modes = ['CoffeeScript'];
      $scope.mode = $scope.modes[0];

      $scope.aceOption = {
        mode: $scope.mode.toLowerCase(),
        onLoad: function (editor) { 
          // defaults 
          editor.setTheme("ace/theme/monokai");
           // options
           editor.setOptions({
            showGutter: true,
            showPrintMargin: false,
           });

          $scope.modeChanged = function () {
            editor.getSession().setMode("ace/mode/" + $scope.mode.toLowerCase());
          };

        }
      };

      //Runs every time the value of the editor is changed
        $scope.aceChanged = function(_editor){
          console.log('Ace editor changed');
          // Get Current Value
          var currentValue = _editor.getSession().getValue();
          // Set value
          _editor.getSession().setValue('This text is now in the editor');
        };
});


<div class="wrapper" ng-controller="AceCtrl">
  <section >
    <select ng-model="mode" ng-options="m for m in modes" ng-change="modeChanged()" autofocus="0"></select> 
    <div ui-ace="aceOption" ng-model="aceModel" class="ace_editor"></div>
  </section>
   <div ng-change="aceChanged" style="border:1px solid red; position:relative; width:50%; height:300px; float:right;"></div>
</div>

1 个答案:

答案 0 :(得分:9)

如果你想在ui-ace的onChange处理程序中执行此操作,你可以从编辑器的会话中获取文档并获取它的值:

editor.getSession().getDocument().getValue();

参考:http://ajaxorg.github.io/ace/#nav=api&api=document

示例代码:

<div ui-ace="{
    onLoad: aceLoaded,
    onChange: aceChanged
}"></div>
<textarea id="ace_document">
    {{aceDocumentValue}}
</textarea>

$scope.aceLoaded = function(_editor) {
    $scope.aceSession = _editor.getSession();
};
$scope.aceChanged = function () {
    $scope.aceDocumentValue = $scope.aceSession.getDocument().getValue();
};

关于Plunker的工作示例:http://plnkr.co/edit/9swlVY9JnIfOnbOAfXui?p=preview

但最简单的方法是将值赋值给范围并在指令元素上使用ng-model:

控制器:

angular.module('app').controller('rootController', [
    '$scope',
    function ($scope) {
        $scope.aceValue = 'Foobar';
    }
]);

模板:

<div ui-ace ng-model="aceValue"></div>
<textarea id="ace_document" ng-model="aceValue"></textarea>

关于Plunker的工作示例:http://plnkr.co/edit/fbtzYDEqIQEwB6Ascm3s?p=preview