Reputation: 16130
I have a controller like this (with a bunch of stuff removed):
function SignupController($scope) {
function isDateOfBirthValid(day, month, year) {
// Process day, month and year and return a bool...
// Also update the view model with the appropriate validation message
}
}
The function isDateOfBirthValid() is used internally by the controller, but I would also like to be able to call it from external code.
(I expect I'll be told this contravenes the Angular pattern, but it really would save me a bunch of time...)
How do I need to change the controller so that I can call this function externally? I can't just move the function outside the controller, because the function modifies the view model's state in a way which is important.
Upvotes: 1
Views: 1419
Reputation: 39926
Your function should be seperated between concerns. Its name isDateOfBirthValid
really doesn't imply that it should have any side effects.
The part of the function that has side effects should be moved into a service that possess the business model. Your controller only has to reflect the content of the model. The controller is not the model.
This answers deals with how to update a service from outside of angular.
Upvotes: 0
Reputation: 1573
You can use angular services for example
SERVICE CODE
app.service('CommonFunctions', function() { this.isDateOfBirthValid = function(day, month, year) { /// your code here }; this.function2 = function() { // your code here }; });
Controller CODE
Option 1
function SignupController($scope , CommonFunctions) {
$scope.isValidDOB = CommonFunctions.isDateOfBirthValid (1,2,2013);
}
Option 2
var app = angular.module('app'); app.controller('SignupController', function($scope, $location, $routeParams, CommonFunctions) { $scope.isValidDOB = CommonFunctions.isDateOfBirthValid (1,2,2013); });
Upvotes: 2