简体   繁体   English

在MVC中使用AngularJ时,请保持视图的强类型化

[英]Keep the Views strongly typed when using AngularJs in MVC

One of the main reasons I love MVC is that both the Views and the Controllers are strongly typed. 我喜欢MVC的主要原因之一是视图和控制器都是强类型的。 This means I can call a variable defined in the Model directly from the View using the Razor syntax: 这意味着我可以使用Razor语法直接从View调用Model中定义的变量:

<p>
    @Model.MyProperty // strongly typed
</p>

While doing so, Visual Studio will provide intellisense, smart refactoring options etc. The advantages of that are obvious. 在此过程中,Visual Studio将提供智能感知,智能重构选项等。其优势显而易见。

Instead, if I decide to use AngularJs (or any other client-side UI framework, actually), my view will look like this: 相反,如果我决定使用AngularJ(或实际上是任何其他客户端UI框架),则我的视图将如下所示:

<p>
    {{myProperty}} // this is just a string!
</p>

No intellisense, no refactoring options... I'm left alone here, because the IDE doesn't know what {{myProperty}} is and where it's defined. 没有智能,没有重构选项……我在这里一个人呆着,因为IDE不知道{{myProperty}}是什么以及它的定义位置。 In other words, there is no contract between the View, the Model and the Controllers other than the personal knowledge that the developer has of the structure of the application and the name of its variables. 换句话说,除了开发人员对应用程序的结构及其变量名称具有的个人知识之外,视图,模型和控制器之间没有契约。

Since all my Angular models are associated to a Typescript interface , is there any tool that will give me intellisense in the Views based on those Typescript interfaces? 由于我所有的Angular模型都与Typescript接口相关联,是否有任何工具可以基于这些Typescript接口在视图中赋予我智能?

After doing some research, it doesn't seem that this specific functionality (intellisense in HTML for TypeScript) is fully supported in any editor. 经过研究后,似乎没有任何编辑器完全支持此特定功能(用于TypeScript的HTML中的智能)。 However, you can install plugins in some to get autocomplete functionality for names (because the bracket syntax is specific to Angular and other front-end frameworks); 但是,您可以在其中安装插件以获得名称的自动完成功能(因为括号语法特定于Angular和其他前端框架); there are extensions for VS, VS Code, WebStorm: VS,VS Code,WebStorm都有扩展:

-- -

Also, this blog post might not solve your problem, but might work if you approach the problem differently: Strongly Typed Views with AngularJS 另外,此博客文章可能无法解决您的问题,但是如果您以不同的方式解决问题,则可能会起作用: 使用AngularJS的强类型视图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM