faboolous faboolous - 15 days ago 7
AngularJS Question

angular and plain javascript functions, best practice

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.

Answer

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
Comments