0

New to angular.js.

Are there any drawbacks of using $scope with every function declared in the applications controller though we don't intend to use them in the view? in the below example is there any drawback or advantage of following the "example 2" style of coding?

In both the examples we intend to show only the someFunc1 in the view

Example 1

var app = angular.module('def',[]);
app.controller('abcctrl' , []) {

    $scope.function someFunc1(){
        someFunc2();
    }

    function someFunc2(){
    }

}]);

Example 2

var app = angular.module('def',[]);
app.controller('abcctrl' , []) {

    $scope.someFuc1  = function(){
    $scope.someFunc2();
    };

    $scope.someFuc2 = function(){
    };

}]);

1 Answer 1

1

Yes, Example 2 has drawbacks in regards to maintainability and readability. If you don't intend to use the function in your view, don't put it on $scope.

Exposing extraneous functions on your $scope ends up making your code harder to read and understand for the next person. The next person maintaining the app might ask "Why is this here?", they might even make incorrect assumptions about it's usage. Having a function exposed on your $scope sends a clear message that the function is needed on the view.

If you leave unnecessary functions off $scope it is very easy to recognize them as an internal or private function that the view doesn't need to worry about. This keeps things less confusing.

If you have time, I recommend reading the widely accepted coding style guide for angular applications written by the famous John Papa.

https://github.com/johnpapa/angular-styleguide

Side Note:

Assigning things to $scope is the "old way" of doing things. Unfortunately you will find many examples online using $scope because it was around quite a while before the angularjs team came up with an easier, more readable way to bind things. There is a new way called the "controller-as" method. It is covered in the guide above.

Sign up to request clarification or add additional context in comments.

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.