gpt4 book ai didi

javascript - AngularJS 哲学 - Controller 作为 "windows"到服务

转载 作者:数据小太阳 更新时间:2023-10-29 04:46:23 27 4
gpt4 key购买 nike

抱歉标题模糊;

我一直在重构我的一些 AngularJS 代码,试图让它更“有 Angular ”,我注意到这种模式经常出现:

app.service("someService", function(...) {
...
}

app.controller("ControllerForThisSection", function($scope, someService) {
$scope.someService = someService
}

基本上, Controller 的主要作用是为范围提供对服务的引用,以便 View 可以使用它,例如

<div ng-if="someService.status">
....
</div>

所以我有多个 Controller ,它们只依赖于某些共享数据或服务,并用于引用通过范围可用的那些服务。

使用这种设计有什么缺点吗?我可以改进我的想法吗?这是做到这一点的“Angular ”方式吗?

感谢您的任何建议!

最佳答案

这就是“Angular 方式”。共享数据应放入服务中,然后在需要的地方注入(inject)。

我喜欢主要从模型(通常存储在服务中)和 View 的 Angular 来考虑我的 Angular 应用程序。 Controller 只是粘合剂,让我们能够投影/提取特定 UI View 所需的模型部分。

此外,将服务视为返回模型 API,而不是模型对象(到 quote Josh)。

关于javascript - AngularJS 哲学 - Controller 作为 "windows"到服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17228173/

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