javascript - 将 $scope 传递给 Angularjs 中的服务是否不合适,如果是,为什么?

标签 javascript angularjs angularjs-scope

是否有充分的理由不应将 $scope 传递给服务?

我意识到服务是可重用的单例,因此将(可能)大对象传递给服务可能会出现维护问题,但让我们假设可靠的文档会声明“$scope 的以下成员是必要的。”我只是觉得它看起来比传入 4-6 个参数更干净。

对于这种做法的任何其他问题将不胜感激。我正在对这段代码进行评估! :)

顺便说一句,我刚刚意识到 angularJS 社区在这里的活跃程度,我非常感激!!

最佳答案

阅读这篇文章 5 Guidelines For Avoiding Scope Soup in Angular

在第 5 点中,他解释了不将 $scope 传递给服务的原因。

我会在这里引用他的一些文章

The problem with relying on values to be set from a parent controller, or relying on a child controller to set data back up on the parent scope, is that you end up with an implicit coupling that isn't easy to see at first.

Worse, it means the controller implementation is completely dependent on the ordering of the bindings in the view! I can't use or test those controllers independently of each other, because they are coupled together by $scope.

$scope 应该用作 View 和 Controller 之间的粘合剂。如果您想从 $scope 向服务发送一些值,只需提取这些值并将它们传递给服务即可。

如果您发现必须传递太多值,请考虑将对象中的值分组,然后传递它们。

更改 $scope 中的一些内容可能会以不需要的方式影响您的应用。

在 Controller 外部使用 $scope 是一种反模式。

关于javascript - 将 $scope 传递给 Angularjs 中的服务是否不合适,如果是,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901670/

相关文章:

angularjs - 将 Angular-fullstack 部署到 Azure

javascript - 从指令更新指令上的 ngModel

javascript - 使一个 Controller 依赖于另一个 Controller 的范围

css - 将 ui-select 样式替换为原始样式

java - 如何在不使用复选框或单选按钮的情况下将表格中选择的数据发送到 Struts2 中?

Angularjs获取子数组id

angularjs - Angular.js 传递范围属性作为对指令的引用?

angularjs - 如何使用 angularjs 在 ionic 中制作简单的按钮导航

javascript - html/javascript 如何使用按钮单击方法显示用户输入?

javascript - Google DoubleClick for Publishers 失败得太悄无声息