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.

rtan
  • 55
  • 8

2 Answers2

1

This would work:

$scope.adddata = adddata;

instead of:

$scope.adddata = adddata();

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

CD..
  • 72,281
  • 25
  • 154
  • 163
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).

Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90