0

When do we need to bind an method to $scope in controller,i am dealing with methods which is just mapping operation on object.

Example :
$scope.myVar = {};

     function myMyObject(x) {
          $scope.myVar = {
                  "xKey":x
           }

     }

    to 

    $scope.myMyObject = function(x) {
          $scope.myVar = {
                  "xKey":x
           }

     }

    myMyObject(10);
    $scope.myMyObject(10);
Is it necessary to bind $scope to myMyObject method here ?
jsduniya
  • 2,464
  • 7
  • 30
  • 45
  • 2
    no. you need to use $scope only for the methods called or need to be called from view. – Ved Oct 28 '15 at 11:04
  • No, its not nessesery. You can bind to `this` and use `controllerAs` syntax in the view - https://docs.angularjs.org/api/ng/directive/ngController#example – Krzysztof Safjanowski Oct 28 '15 at 11:15

4 Answers4

1

Bind methods to $scope only when they will need to be called from the View. If they are just private methods that you only call from the controller itself, there's no need to pollute the scope.

In your specific scenario, there is no need to bind myMyoObject() to the scope.

Edit: You can avoid using $scope altogether and use controllerAs syntax, in which case instead of binding to $scope, you bind to this. The non-public functions still will be kept unbound to anything.

Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
1

Only methods defined on $scope object are accessible from the HTML/view. Example from ng-click, filters, etc. -If your method is not required to be accessed from html , then there is no need to bind it to $scope.

Disha
  • 822
  • 1
  • 10
  • 39
1

As a good practice, you can declare all your functions in your controller and then bind to the $scope only the functions you need.

Example:

function _myHelperFunction(param) {
    //do some stuff
}

function myFunction(otherParam) {
    //do some stuff or use the _myHelperFunction
}

function myFunction2(otherParam) {
    //do some stuff or use the _myHelperFunction
}

function myFunction3(otherParam) {
    //do some stuff or use the _myHelperFunction
}

$scope.myFunction = myFunction
$scope.myFunction2 = myFunction2
$scope.myFunction3 = myFunction3

Or even better with ES6 destructuring

[$scope.myFunction, $scope.myFunction2, $scope.myFunction3] =
[myFunction, myFunction2, myFunction3]

Or:

angular.extend($scope, {
    myFunction,
    myFunction2,
    myFunction3
})
0

Keep independent function in the controller itself.

Adding all functions to the $scope will effect the application performance in long run and in complex apps with large functions

write function in $scope only if you want to access it in the html(view/partial) or in child $scopes

function written in parent $scope is accessible for the child $scopes

Arun Ravindranath
  • 2,011
  • 1
  • 12
  • 14