0

I'm trying to add function to controller in angularJS, the way I think should be working but sadly not.

Here is my code.

//this is working.
$scope.adddata = function () {
    $scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
    //$scope.names.push($scope.newdata);
}


//this is not working
function adddata() {
$scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
//$scope.names.push($scope.newdata);
}
$scope.adddata = adddata();

Both functions above are in the definition of controller, hence $scope variable is available.

Can I only use $scope.functionname = functionname(){....}

or I can create a function and later assign it to controller / scope.

2 Answers 2

1

Do $scope.adddata = adddata; (no parentheses). Using the parentheses will assign the result of calling adddata() to the scope variable, which is undefined (adddata() does not return a value).

Sign up to request clarification or add additional context in comments.

Comments

1

This would work:

$scope.adddata = adddata;

instead of:

$scope.adddata = adddata();

Don't invoke the function, pass a reference to it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.