I find angular scope functions challenging to work with due to their lack of a clear contract. They extract parameters from the scope and store results back into the scope, rather than explicitly defining function parameters and returning a result. Consider this example (plunkr):
HTML
<html ng-app="exampleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="myctrl.js"></script>
</head>
<body ng-controller="MyCtrl">
Here are my parameters:
<input type="number" ng-model="first"> + <input type="number" ng-model="second">
<button ng-click="sum()">Sum it!</button>
<p>{{result}}</p>
</body>
</html>
JS
//myctrl.js
var app = angular.module('exampleApp', []);
app.controller('MyCtrl', function($scope) {
$scope.sum = function() {
$scope.result = $scope.first + $scope.second;
}
});
When these functions get longer than 10 lines, understanding the main purpose can become difficult. Additionally, I struggle with documenting them using jsdoc. Are there any best practices for creating more effective functions in angular?
P.S. The example provided is simplified; typically my functions would involve querying an angular service and processing the result for display.
P.P.S. Although many recommend using the controller as
syntax, I believe it doesn't fully address the issue as the function still lacks a return value and relies heavily on side-effects.