0

Is there any difference (maybe in performance) between this style of adding functions to (angular) scripts, or are they essentially equivalent:

Option 1: function inside controllers

AngularApp.component('component', {
    templateUrl: '/domain/app/component.html'
    , controller: function ($scope,$rootScope,api) {

        $scope.var = false;
        getBackendData();

        //get data about available io_engines from the backend
        function getBackendData() {
            console.log("loading backend data...");            
            api.get().then(
                function (response) {                   
                    console.log("Backend data loaded.");
                })
                .catch(function (err) {
                    console.log("Error getting data from backend");
                    console.log(err);
                });
        }
   }

});

Option 2: function outside the controller

 AngularApp.component('component', {
        templateUrl: '/domain/app/component.html'
        , controller: function ($scope,$rootScope,api) {

            $scope.var = false;
            getBackendData();
       }
    });


    //get data about available io_engines from the backend
    function getBackendData() {
                console.log("loading backend data...");            
                api.get().then(
                    function (response) {                   
                        console.log("Backend data loaded.");
                    })
                    .catch(function (err) {
                        console.log("Error getting data from backend");
                        console.log(err);
                    });
     }

I (think to) understand getBackendData() in the second option becomes a global function, but I am not very clear about implications.

0

2 Answers 2

2

If you define a function in a component, you will have one function definition per component instance, so in theory it will take more memory.

In the second example, you will only have one function per application.

But such difference is really academic. The bigger issue here is that these kind of functions should be defined in (or as) a service, so they can be:

  • tested
  • possibly reused in other places
  • mocked in the component tests
Sign up to request clarification or add additional context in comments.

Comments

1

The Option 1 is better because you are not polluting the global scope. Let say that is not a good practice. I suggest you to follow a style guide like this by Todd Motto:

https://github.com/toddmotto/angular-styleguide/tree/angular-old-es5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.