gpt4 book ai didi

angularjs - 如何使用变量将对象键传递给 Angular 指令?

转载 作者:行者123 更新时间:2023-12-04 02:51:05 26 4
gpt4 key购买 nike

我正在使用 Code Mirror将文本区域格式化为代码的指令。

什么是有效的:

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

你可以这样设置选项

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

在你的 Controller 中:

$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]".

我认为指令有问题,没有意识到变量已经改变。

最佳答案

如果不 fork ui-codemirror,我认为这对您不起作用。 UI-codemirror 中的代码在开始时执行 opts = angular.extend({}, options, scope.$eval(attrs.uiCodemirror));,但它不会监视更新。

如果你从:https://github.com/angular-ui/ui-codemirror/blob/master/ui-codemirror.js fork 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) ??
}
});

那么它可能会起作用,但我还没有测试过,所以我不知道它是否真的会起作用。也许这会让您了解如何创建所需的指令。

另一种方法会更繁重,它是实例化两个代码镜像并在两者之间切换......但我真的不太喜欢这个选项。

关于angularjs - 如何使用变量将对象键传递给 Angular 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17706809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com