rtan
rtan

Reputation: 55

Adding function to controllers in AngularJs

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.

Upvotes: 0

Views: 116

Answers (2)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

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

Upvotes: 1

CD..
CD..

Reputation: 74096

This would work:

$scope.adddata = adddata;

instead of:

$scope.adddata = adddata();

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

Upvotes: 1

Related Questions