3

Code Mirrorディレクティブを使用して、テキスト領域をコードとしてフォーマットしています。

何が機能していますか:

<textarea ui-codemirror type="textarea" ng-model="x"></textarea>

オプションを次のように設定できます

<textarea ui-codemirror="editorOptions" type="textarea" ng-model="x"></textarea>

そしてコントローラーで:

$scope.editorOptions = {
            name: 'javascript',
            json: true,
            smartIndent: false,
            tabSize: 2,
            lineWrapping : true,
            lineNumbers: true,
            mode: 'javascript'
        }

機能していないもの:

モデルの別の部分に基づいて editorOptions を動的に変更しようとしています (Javascript と Markdown をサポートしています)。

だから私はこれを試しています:

$scope.editorOptions = {
        json: {
            name: 'javascript',
            json: true,
            smartIndent: false,
            tabSize: 2,
            lineWrapping : true,
            lineNumbers: true,
            mode: 'javascript'
        },
        markdown: {
            name: 'markdown',
            json: false,
            smartIndent: false,
            tabSize: 2,
            lineWrapping : true,
            lineNumbers: true,
            mode: 'markdown'
        }
    };

そして、これをHTMLで:

<select ng-model='editorType' required ng-options='option.value as option.name for option in editorTypes'></select>
<textarea ui-codemirror="editorOptions[editorType]" type="textarea" ng-model="x"></textarea>

私の質問は、選択モデル (editorType) の値を使用して、コード ミラー ディレクティブで使用されているオプション オブジェクトを指定するにはどうすればよいですか?

私はもう試した

<textarea ui-codemirror="editorOptions.[editorType]" type="textarea" ng-model="x"></textarea>
<textarea ui-codemirror="editorOptions[$scope.editorType]" type="textarea" ng-model="x"></textarea>

すべて役に立たない。

これを行う適切な方法を知っている人はいますか?

大変感謝します!

更新 これは正しい構文だと思います:

ui-codemirror="editorOptions[editorType]".

変数が変更されたことを認識しないディレクティブに問題があると思います。

4

2 に答える 2

3

ui-codemirror をフォークしないと、これがうまくいかないと思います。UI-codemirror 内のコードopts = angular.extend({}, options, scope.$eval(attrs.uiCodemirror));は最初はそうしますが、更新を監視しません。

https://github.com/angular-ui/ui-codemirror/blob/master/ui-codemirror.jsから ui-codemirror をフォークし、次のようなものを追加した場合

attrs.$observe('uiCodemirror', function (newVal, oldVal) {
  if (newVal !== oldVal) {
    opts = angular.extend({}, options, scope.$eval(attrs.uiCodemirror));
    codeMirror = CodeMirror.fromTextArea(elm[0], opts); //or maybe $timeout(deferredCodemirror) ??
  }
});

それならうまくいくかもしれませんが、私はそれをテストしていないので、本当にうまくいくかどうかはわかりません. おそらく、これにより、必要なディレクティブを作成する方法のアイデアが得られるでしょう。

かなり重くなる別の代替手段は、2 つのコードミラーをインスタンス化し、2 つを切り替えることです... しかし、私はそのオプションがあまり好きではありません。

于 2013-07-17T19:54:53.293 に答える
1

ジョナサンの返信に追加:

attrs.$observe('uiCodemirror', function (newVal, oldVal) 
{
  if(newVal !== oldVal) 
  {
    opts = angular.extend({}, options, scope.$eval(attrs.uiCodemirror));
    var keys = Object.keys(opts)
    if(keys.length != 0)
    {
      keys.forEach(function(i)
      {
        var v = opts[i];
        codeMirror.setOption(i, v);
      });

      $timeout(function() { codeMirror.refresh()} );
    }
  }
});
于 2014-02-06T05:30:46.147 に答える