gpt4 book ai didi

javascript - 是否应该避免在 AngularJS Controller 中包含常规 Javascript 对象?

转载 作者:行者123 更新时间:2023-11-28 15:28:14 25 4
gpt4 key购买 nike

我正在阅读 Adam Freeman 的《Pro AngularJS》,我对书中的一个示例有一个挑剔的问题:

myApp.controller("tomorrowCtrl", function($scope) {
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday";]
$scope.day = dayNames[(new Date().getDay() + 1) % 7];
});

我明白这个 Controller 的总体目的是:通过 $scope.day 在 View 上显示星期几的名称。但我很困惑为什么 Controller 使用普通的 Javascript 数组 - var dayNames - 来创建 $scope 对象。

AngularJS controller documentation解释说 Controller 用于:

set up the initial state of the $scope object [and to] add behavior to the $scope object.

果然,dayNames 有助于设置 $scope 对象的初始状态。它还包含一些应用程序的业务逻辑,所以我猜它有点检查。我担心的是,我还没有找到任何其他遵循这种设计模式的 AngularJS Controller 示例;我在 Angular Controller 文档和 PhoneCat 教程中都没有找到任何内容。

像这样在 AngularJS Controller 中包含普通的 Javascript 对象有意义吗? (这被认为是无害的吗?)

如果没有,为什么?是否有任何充分的理由在 Controller 中包含普通的 Javascript 对象?另外,是否有不同的方式让 dayNames 适合 Angular 架构,例如指令或服务?

最佳答案

您会在书籍和互联网上看到很多类似的示例。关键是,$scope.day 设置为某物,并且我确定它如何在您的 View 中反射(reflect)它。

您可以拥有外部纯Javascript逻辑并在AngularJS中使用它,它显然不会破坏任何东西,但通常最好的做法是在 Controller 之外完成所有范围操作/业务逻辑服务/工厂/提供商。为什么要反对 angularJS 并使用外部的东西?你想坚持 angularJS 的流程。

假设它正在做一些更复杂的事情,它可能看起来更像这样:

myApp.factory("tomorrowService", function() {
// factory's can be written in many different patterns
// this is just for examples sake
return {
getDays : function () { /* return stuff */ }
}
});

myApp.controller("tomorrowCtrl", function($scope, tomorrowService) {
$scope.day = tomorrowService.getDays();
});

使用 tomorrowService 中的方法执行所有业务逻辑并返回某种结果。

我发现这篇文章( http://toddmotto.com/rethinking-angular-js-controllers/ )非常有用,可以帮助您更好地了解如何制作 Controller 以及在 angularJS 项目中有益的分离。

关于javascript - 是否应该避免在 AngularJS Controller 中包含常规 Javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28351458/

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