davej / angular-classy

Cleaner class-based controllers with Angular 1
http://davej.github.io/angular-classy/
813 stars 27 forks source link

Add functions to "Controller as" alias #19

Closed meenie closed 10 years ago

meenie commented 10 years ago

These days I never actually add anything to the scope directly, I always add it to this within a controller. Something like this:

app.config(function config($stateProvider) {
    $stateProvider.state('fooState', {
        url: '/foo',
        controller: 'FooCtrl as FooCtrl',
    });
}).controller('FooCtrl', function() {
    var Ctrl = this;

    Ctrl.myCoolFunction = angular.noop;
});

Then in my view, I call the function like FooCtrl.myCoolFunction().

I noticed that you do automatically do the 'Controller as' syntax, which is great. But it would be much better if all the functions you are adding get added to the Controller rather than directly on the scope. Something like this:

app.config(function config($stateProvider) {
    $stateProvider.state('fooState', {
        url: '/foo',
        controller: 'FooCtrl',
    });
}).classy.controller({
    name: 'FooCtrl',
    inject: [],
    init: function() { },
    myCoolFunction: angular.noop
});

And then in the view, you can do FooCtrl.myCoolFunction().

meenie commented 10 years ago

I've just been looking at https://github.com/davej/angular-classy/blob/master/examples/todomvc/js/controllers/todoCtrl-asController.js and it looks like this already being done :). Do you have to do addFnsToScope: false for this to work? Or are you just making a point that the functions are not added directly to the scope?

davej commented 10 years ago

Hi Cody — Yup, you can do it at the controller or the module level. See the third FAQ (at the bottom) here: http://davej.github.io/angular-classy/

meenie commented 10 years ago

Alright, thanks :). I do remember reading that, just forgot about it ><. Closing.

davej commented 10 years ago

Also you should be aware that chaining (like in your example) won't work if you have more than one Classy Controller. See #13.

meenie commented 10 years ago

I never do more than one controller per module, so no worries :). My above example should still work okay.