kipris
kipris

Reputation: 3039

Angular: get input values in js function

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

Upvotes: 0

Views: 74

Answers (3)

asdf_enel_hak
asdf_enel_hak

Reputation: 7650

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)
                //..
    }    

Upvotes: 3

tufac2
tufac2

Reputation: 778

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.

Upvotes: 2

Babu Swami
Babu Swami

Reputation: 798

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;
            }
    } 
});

Upvotes: 0

Related Questions