1

New to Angular and I'm trying to follow JSLint ( written by Douglas Crockford ) recommendation of not using this in JS at all.

How can I prevent myself to use this in Angular? All the tutorials I've seen so far rely on using this and SO search had resulted in no answer.

For the purpose of being clear, let's assume I'm trying to write this controller:

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

How can I access the controller object so I can add the products property?

var my_controller = app.controller('StoreController', function() {
});
my_controller.products = {}; // Maybe like this?
Sam Hosseini
  • 813
  • 2
  • 9
  • 17

1 Answers1

2

Inject $scope, for example:

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

Here is more information about them: https://docs.angularjs.org/guide/scope


Also, when using things like services, you can avoid this by keeping a local state and returning an interface object. For example:

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

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

        }
    };
});

I would just like to note though, that I don't see any good reason why you should avoid this when using angular. I think using $scope has more semantic usefulness when reading controller code, but when using things like services, I write less code by creating exposed functions like this.somefunc = ....

Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • Thanks for the quick reply. In JS, he had decent reasons not to use 'this'. I had the assumption that it applies to Angular, or any other JS framework. Based on your reply and other people's comments, apparently it doesn't. – Sam Hosseini Jan 21 '16 at 23:35