Below we have an example controller that has several methods for geometric calculations on a right triangle.

app.controller('TriangleController', ['$scope', function ($scope) {
// here we have a triangle object
    $scope.triangle = {
        base: undefined,
        height: undefined
    };

    $scope.findArea = function () {
        $scope.area = 0.5 * $scope.triangle.base * $scope.triangle.height
    };

    $scope.calculateHyptenuse = function () {
        var b = $scope.triangle.base;
        var h = $scope.triangle.height; 
        $scope.hypotenuse = Math.sqrt((b * b) + (h * h))
}
}])

This is a perfect example of something that we don't want in our controllers. We do not want to see a bunch of logic in our controllers. Remember, we want our controllers to be thin. Their only job is to render data to our view and listen for user actions.

One of the main objectives of good coding is to be able to reuse it. Right now these functions only calculate the area and hypotenuse of one triangle; the $scope.triangle object we defined before. Also it can only be used in this controller since it is where we defined the functions.

Let's use an angular service (app.service) to abstract these functions to deal with any triangle parameters.

Exercise:

  1. Take the methods that calculate the area and hypotenuse of a right triangle and put them in an angular service.

  2. Create a view where a user can input the base and height of a right triangle. Include two buttons that calculate and display the area and hypotenuse of that triangle.