在AngularJS中,为什么我应该在范围对象名称的开头使用$?

时间:2015-06-14 18:07:29

标签: angularjs angularjs-scope

没有JS经验。学习AngularJS

所以我读过https://docs.angularjs.org/guide/scope, 我已经看了一些stackoverflow.com answers关于JavaScript在JavaScript中使用的内容。我知道$在某些库中有特定的用途,比如JQuery,而在较新版本的JavaScript中,它只被视为变量名的标准字符。所以我的问题是......

为什么在AngularJS中看到一个带有$前面的范围对象很常见,即使$ isn不是必需的?

An example of an AngularJS scope object without using a $

没有$

的范围对象
app.controller('MainController', ['$scope', function(withoutdollarsign){
    withoutdollarsign.title = 'string here';
}]);

或 $

的范围对象
app.controller('MainController', ['$scope', function($withdollarsign){
    $withdollarsign.title = 'string here';
}]);

2 个答案:

答案 0 :(得分:1)

Angular API documentation州:

  

Angular Prefixes $和$$:为了防止与您的代码意外发生名称冲突,Angular将带有$的公共对象的名称和带有$$的私有对象的名称作为前缀。请不要在代码中使用$或$$前缀。

在您的代码段中,您将展示一种处理依赖注入的方法。在此方法中,传递参数数组,并且数组按顺序与传递给函数的参数匹配。按照惯例(但不是强制性的),对数组值使用与传递给函数的值相同的名称。使用不同的名称可能会在代码中造成混淆,特别是对于稍后查看代码的人,乍一看withoutdollarsign实际上$scope可能不会理解。

实际上,$$$用于帮助您作为开发人员识别由框架创建的对象与在您自己的代码中创建的对象。对于这种用法,JavaScript语言没有特殊意义,它只是Angular贡献者使用的约定。

正如此处所述,建议您在与Angular Framework进行交互时不要在自己的代码中使用$$$

答案 1 :(得分:0)

您无需在此处使用美元符号。大多数人使用$scope作为函数参数,因为它很容易识别,通常使用注入组件的名称作为参数名称。但一般来说,它只是一个变量名称,你可以使用你想要的任何名称。

函数参数名称的唯一情况,如果您将其用于依赖注入:

// This will work
app.controller('MainController', function($scope){
    $scope.title = 'string here';
});

// This will not work, angular tries to find a `abcdef` component to inject
app.controller('MainController', function(abcdef){
    abcdef.title = 'string here';
});

但是因为你使用数组表示法(推荐),所以你不需要这个。

相关问题