简体   繁体   中英

AngularJS Methods attached to the scope vs within the scope of the controller

I am starting to re-factor the project we have been working on for a couple of months. There has been a lot learned about Angular along the way, and many of this will be implemented in the re-factoring.

During this process I am noticing a lot of methods attached to the $scope of, say, a controller. Some of which aren't actually called by anything in the view or watched, or for that matter doing anything else other than fire and forget.

So it got me to thinking. If a method is not required by any views, or having its result watched would there be any performance gains by not attaching these methods to the $scope ?

For example, Lets say, in a controller, I am asynchronously saving some data - fire and forget sort of stuff.

Would this:

saveState();    
function saveState(){
       // do my saving here. don't need to return anything
}

Give me any performance gains over this:

$scope.saveState();    
$scope.saveState = function(){
     // do my saving here. don't need to return anything
}

You just discovered something very true. I would actually say it is bad to do that because cause you are polluting the scope. $scope should only have properties on it that directly need to be used by a view. You may not notice the performance gains with smaller apps but when you get into the 50+ controller range with thousands of data points in scope, ever little bit can help. I did a little write up at Coderwall ( https://coderwall.com/p/nsanaa?i=1&p=1&q=author%3Abreck421&t%5B%5D=breck421 ) about js profiling with flame chart. It may help you put some numbers to your conclusions.

I took your thoughts a step further and created a init load model for my controllers.

MyApp.controller('MyController', ['$scope', function ($scope) {
    var self = this;

    this.init = function () {
        this.setScope();
        this.load();
    };

    this.load = function () {
        this.setScopeEvents();
    };

    this.setScope = function () {
        $scope.isLovingStackOverflow = true;
    };

    this.setScopeEvents = function () {
        $scope.answerQuestion = function() { /* answer a question */}
    };

    this.init();
}]);

The beauty with this is that you can call any of the this.* functions from unit tests.

I want to commend you on your thought process change. There are many more in your near future with Angular :)

Thanks,

Jordan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM