AngularJS Angular $scopes Using $scope functions


Example

While declaring a function in the $rootscope has it's advantages, we can also declare a $scope function any part of the code that is injected by the $scope service. Controller, for instance.

Controller

myApp.controller('myController', ['$scope', function($scope){
    $scope.myFunction = function () {
        alert("You are in myFunction!");
    };
}]);

Now you can call your function from the controller using:

$scope.myfunction();

Or via HTML that is under that specific controller:

<div ng-controller="myController">
    <button ng-click="myFunction()"> Click me! </button>
</div>

Directive

An angular directive is another place you can use your scope:

myApp.directive('triggerFunction', function() {
    return {
        scope: {
            triggerFunction: '&'
        },
        link: function(scope, element) {
            element.bind('mouseover', function() {
                scope.triggerFunction();
            });
        }
    };
});

And in your HTML code under the same controller:

<div ng-controller="myController">
    <button trigger-function="myFunction()"> Hover over me! </button>
</div>

Of course, you can use ngMouseover for the same thing, but what's special about directives is that you can customize them the way you want. And now you know how to use your $scope functions inside them, be creative!