簡體   English   中英

如何使用變量將對象鍵傳遞給Angular Directive?

[英]How to use a variable to pass an object key into an Angular Directive?

我正在使用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>

我的問題是 - 如何使用select模型(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]".

我認為指令沒有意識到變量已經改變了。

我不認為這會在不使用ui-codemirror的情況下為你工作。 UI-codemirror中的代碼執行opts = angular.extend({}, options, scope.$eval(attrs.uiCodemirror)); 在開始時,它不會注意更新。

如果您從以下網址分叉ui-codemirror: https//github.com/angular-ui/ui-codemirror/blob/master/ui-codemirror.js然后添加類似的東西

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) ??
  }
});

然后它可能會工作,但我沒有測試過,所以我不知道它是否真的有效。 也許這會讓你知道如何創建你需要的指令。

另一種可能相當重的替代方案是實例化兩個代碼鏡像並在兩者之間切換......但我真的不太喜歡這個選項。

添加到Jonathan的回復中:

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()} );
    }
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM