0

My controller is too big so was decided to split it to several functions. So now functions don't see input values. Could you advice me how to solve this problem?

angular.module("sampleApp", []) .controller("defaultCtrl", function ($scope) { $scope.addNewUser = function (userDetails, isvalid) { doLogin(); } }); var doLogin = function(userDetails, isvalid) { if (isvalid) { $scope.message = userDetails.name + " " + userDetails.email; } else { $scope.message = "Error"; $scope.showError = true; } } 

http://plnkr.co/edit/Rv6dqTECeD62HA1SgDM9?p=preview

    3 Answers 3

    3

    While you call function, you should pass parameters

    $scope.addNewUser = function (userDetails, isvalid) { doLogin(userDetails, isvalid,$scope); } var doLogin = function(userDetails, isvalid, $scope) { //... } 

    http://plnkr.co/edit/G66gFmJVhiXljyxgLDLP?p=preview

    Edit: to get user name length update doLogin function:

     var doLogin = function(userDetails, isvalid, $scope) { if (userDetails) console.log(userDetails.name.length) //.. } 
    1
    • One more question: how can I get userDetails.name' length ?
      – kipris
      CommentedMay 11, 2016 at 10:09
    2

    You have broken down the controller into several functions. However

    var doLogin = function(userDetails, isvalid) { if (isvalid) { $scope.message = userDetails.name + " " + userDetails.email; } else { $scope.message = "Error"; $scope.showError = true; } } 

    is out of the $scope of the controller

    "defaultCtrl"

    So if you want to have smaller controllers you can have several controllers and communicate them using an angular Factory.

    To be honest. I think you should use the same controller to "CONTROL" all the stuff related with your login form.

    2
    • One more question: how can I get userDetails.name' length ?
      – kipris
      CommentedMay 11, 2016 at 10:06
    • userDetails.name.lenght
      – tufac2
      CommentedDec 19, 2016 at 11:49
    0

    You have written your function outside the controller, therefore, the $scope is not available inside doLogin function. Apart from this, you did not pass values userDetails and isvalid values to doLogin call.

    Replace your code with this:

    angular.module("sampleApp", []) .controller("defaultCtrl", function ($scope) { $scope.addNewUser = function (userDetails, isvalid) { doLogin(userDetails, isvalid); } var doLogin = function(userDetails, isvalid) { if (isvalid) { $scope.message = userDetails.name + " " + userDetails.email; } else { $scope.message = "Error"; $scope.showError = true; } } }); 

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.