1

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.

David
  • 15,750
  • 22
  • 90
  • 150

2 Answers2

2

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);
});
Anup Singh
  • 1,513
  • 3
  • 16
  • 32
  • 2
    This all makes sense but it doesn't answer the question, which is how to call that validation method from outside of an Angular construct (i.e. a jQuery plugin). The problem relates to sharing code between jQuery plugins and Angular ... if that's even a valid problem. Perhaps if the plugin is initialized with a directive this problem will go away. – backdesk Oct 23 '13 at 12:16
  • 1
    Take a look at http://stackoverflow.com/questions/16935095/correct-way-to-integrate-jquery-plugins-in-angular-js – backdesk Oct 23 '13 at 12:20
0

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.

Community
  • 1
  • 1
Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
  • Perhaps `validateDateOfBirth()` would be a better name. It's normal for validation logic to have side effects such as showing messages and modifying CSS classes. And these sorts of things affect the view model, which I don't believe I can touch outside the controller. – David Oct 23 '13 at 12:05