Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

Implement functions in link or pass $scope to function outside link


My questions is what is best practice + more efficient? Implementing functions that use $scope inside the Link function, or implemet it outside and pass $scope to it?

angular.module('exampleModule', [])
    .directive('exampleDirective', ['$http',
        function ($http) {
            return {
                restrict: 'EA',
                scope: {
                    ...
                },
                link: function ($scope, element, attr) {
                    /* Implement here? */
                    function myFunc(){
                        /* do some calc using $scope*/
                    }
                },
                templateUrl: "..." 
            }

            /**
            * Assistant Functions
            */
            /* Implement here? */
                function myFunc($scope){
                    /* do some calc using $scope*/
                }
        }]);

Solution

  • you can define the function at bottom, and just give the reference to that function, and that function will receive all the arguments when it will be for ex.

    angular.module('exampleModule', [])
        .directive('exampleDirective', ['$http',
            function ($http) {
                return {
                    restrict: 'EA',
                    scope: {
                        ...
                    },
                    link: myFunc, // just the reference to the function to be invoked
                    templateUrl: "..." 
                }
    
                //link function
                function myFunc($scope, element, attr){
                     /* do some calc using $scope*/
                     $scope.someResult = calculateSomeResult($scope.someArg);
                     // use the sub function to perform calculation and give only required thing as argument, don't pass entire $scope
                }
    
                function calculateSomeResult(someArg) {
                    return someArg * 2; //here perform any calculation or anything. and return the result
                }
            }]);
    

    its not necessary that you have pass anonymous function always you can pass any function reference and when that function will be invoked it will be given the three argument so you can get that argument directly in your function no need to create extra layer of scope and function.