javascript - AngularJS:$scope 与此:$scope 的用途是什么?

标签 javascript angularjs angularjs-scope

我在 AngularJS style guide 中找到了这个

Prefer using controller as syntax and capture this using a variable:

这意味着我可以通过这个将我的所有功能和模型分配给 Controller ,并通过 View 中的别名进行访问。如果这样做,我发现我真的不再需要 $scope 了。一个异常(exception)是当我想访问 $rootScope 中的内容时。

因此,考虑到引用的建议,如果我对访问 $rootScope 中的任何内容不感兴趣,我应该什么时候使用 $scope

也就是说,我是否应该将所有内容都移动到 Controller 的 this 中?如果不是,那么什么应该保留在 $scope 中?

最佳答案

when should I use $scope at all if I'm not interested in accessing anything in the $rootScope?

  • $scope 不仅仅用于访问 $rootScope 中的属性或函数。 示例(顺便说一句,不是太频繁):假设您需要更新一个 DOM 元素而不是 Angular 方式,这意味着通过任何修改组件值(视觉)的外部库来更新它,但是组件的 ng-model 没有得到更新,而您需要它!该怎么办?简单:$scope.$digest(根据您的操作,可能需要任何其他 Angular 函数)。

should I move everything to controller's this?

  • 不,你不知道!实际上,这样做并不是一个好主意。为什么?当您将所有内容移动到 Controller 的 this 时,您就提供了从 View 访问“所有内容”的权限,这是不切实际的,因为您不需要在 View 中将所有内容都声明在 Controller 中。在 Controller 中,有时(大部分时间)你有变量和函数作为其他函数和变量(一种私有(private)的东西)的补充:它们应该在 Controller 内保持“私有(private)”。请参见以下示例:

angular
  .module('myapp', [])
  .controller('foo', function() {

    var vm = this;
    // only this will be available in the view thanks to the controller as syntax
    vm.wizard = {
      userID: null,
      totalCartCount: 0
    }

    // stuff used only inside the controller
    vm.private = {
      subtotalByProducts: [],
      readyToCheckoout
    }

    // only "public" stuff is returned here
    return vm.wizard;

    // functions
  });

If not, then what should stay in the $scope?

您在 $scope 中放入什么完全取决于您,因为它使用 controller as 语法,但请记住 中的所有内容$scope 在 View 中是可访问的。这个想法是减少传递到 View 的变量数量。这在小型网络应用程序中可能不会很明显,但是当应用程序的大小变大时,您会注意到一些变化(加载时间更长等)。

这是每个开发人员的视角问题,以及我们中的任何人对使用最佳实践的喜爱程度。

关于javascript - AngularJS:$scope 与此:$scope 的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952006/

相关文章:

javascript - 按多个键和值过滤,Javascript

Adobe Acrobat 的 JavaScript API - 如何使用 JavaScript 创建指向非 PDF 文档的相对链接?

javascript - 根据输入类型数值创建复选框字段

javascript - 如何修复 prepare statement failed with error : "1" - using SQLite?

angularjs - 如何增加 Angular UI Bootstrap 中的模式宽度?

javascript - 如何让 Controller 等待AngularJS中的工厂响应?

javascript - 使用 localStorage 记住 javascript 警报

java - 向服务器发送 DELETE 时出现错误 405 方法不允许错误

javascript - Angular : update scope inside scope

javascript - 通过公共(public)属性绑定(bind)指令实例