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

标签 angularjs

我在从代码编辑器上输入的任何内容中获取 Ace 代码编辑器结果时遇到问题。

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

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>

最佳答案

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

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:

Controller :
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

关于angularjs - 如何从 ACE-Angular 编辑器中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28241198/

相关文章:

javascript - 为 Angular Directive(指令)提供模型名称以访问其在父级中的范围

javascript - 访问通过启动异步请求的工厂初始化的变量

javascript - 更新 DOM 与在 Angular 中重新渲染 View

javascript - 使用 Angular 平移进行本地化

javascript - 从 AngularJS 中自执行的 Promise 返回一个值

javascript - 输入数据后退出模态

javascript - 文本搜索——过滤两个不同对象/数组中的两个词

javascript - Angular JS 转发器 + Bootstrap 轮播

javascript - AngularJS ng-submit 输入键不起作用

arrays - 使用 MEAN 堆栈存储来自 angularjs 表单的数组数据