javascript - 如何不在 Angular 中使用 'this'?

标签 javascript angularjs

Angular 的新手,我正在尝试遵循 JSLint(由 Douglas Crockford 编写)的建议,即根本不要在 JS 中使用 this

如何防止自己在 Angular 中使用 this?到目前为止,我看到的所有教程都依赖于使用 this 并且 SO 搜索没有得到任何答案。

为了清楚起见,假设我正在尝试编写这个 Controller :

app.controller('StoreController', function() {
    this.products = {};
});

如何访问 Controller 对象以便添加 products 属性?

var my_controller = app.controller('StoreController', function() {
});
my_controller.products = {}; // Maybe like this?

最佳答案

注入(inject) $scope ,例如:

app.controller('StoreController', function($scope) {
    $scope.products = {};
});

以下是关于它们的更多信息:https://docs.angularjs.org/guide/scope


此外,在使用服务之类的东西时,你可以避免this通过保持本地状态并返回接口(interface)对象。例如:

.service('MyService', function(){
    // state
    var mystate = {};

    // interface object
    return {
        someExposedFunc: function(){

        }
    };
});

不过,我想指出的是,我看不出有什么理由应该避免使用 this使用 Angular 时。我想使用 $scope在阅读 Controller 代码时具有更多语义实用性,但在使用服务之类的东西时,我通过创建像 this.somefunc = ... 这样的公开函数来编写更少的代码.

关于javascript - 如何不在 Angular 中使用 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936001/

相关文章:

javascript - Windows 8 javascript/visual studio 2012 中的 console.log()

javascript - value.getTime 不是函数 GraphQL 自定义标量日期

javascript - 用户突出显示输入字段并且未输入任何内容后,Angular JS 会显示错误

javascript - 选择另一个子菜单时隐藏展开的子菜单

javascript - AngularJS : controller fails when minified

javascript - 在 async.each 的帮助下在 foreach 中调用同步函数(带回调)

javascript - lodash sortBy 不适用于秒

javascript - 如何删除创建的 createDocumentFragment 对象?

javascript - ng-model 未定义,多种方式无法从文本框中获取文本

javascript - Angular js,关于ng-change如何更新其他选择控件的选项