Angular的新手,我试图遵循JSLint(由Douglas Crockford编写)建议不要在JS中使用this
。
如何防止自己在Angular中使用this
?到目前为止,我所看到的所有教程都依赖于使用this
而SO搜索没有得到答案。
为了清楚起见,我们假设我试图写这个控制器:
app.controller('StoreController', function() {
this.products = {};
});
如何访问控制器对象,以便添加products
属性?
var my_controller = app.controller('StoreController', function() {
});
my_controller.products = {}; // Maybe like this?
答案 0 :(得分:2)
注入$scope
,例如:
app.controller('StoreController', function($scope) {
$scope.products = {};
});
以下是有关它们的更多信息:https://docs.angularjs.org/guide/scope
此外,在使用服务之类的东西时,可以通过保持本地状态并返回接口对象来避免this
。例如:
.service('MyService', function(){
// state
var mystate = {};
// interface object
return {
someExposedFunc: function(){
}
};
});
我只想注意,我认为在使用角度时你不应该避免使用this
。我认为在阅读控制器代码时使用$scope
有更多的语义用处,但在使用服务之类的东西时,我通过创建像this.somefunc = ...
这样的公开函数来编写更少的代码。