Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing scope variable to function in ng-click

So I know I must be missing some basic part of javascript with this quesiton but here it goes anyhow:

I have a contoller that has a variable declared in it:

$scope.IsStartDatePickerHidden = true;
$scope.IsEndDatePickerHidden = true;

I have a button that has its ng-click set to go to a function in my controller. This function would be nice if it took in a parameter which it can change the value:

<button type="button" ng-click="showDatePicker(IsStartDatePickerHidden)" >

 $scope.showDatePicker = function(showDatePicker)
 {
     showDatePicker = false;
 }

when I step through this code the function showDatePicker changes the value of the parameter that is passed in but does not seem to change the value of the variable in the controller, so nothing happens. I am sure this has to be something to do with passing by reference. I am just not sure how to pass this in so that $scope.IsStartDatePickerHidden or $scope.IsEndDatePickerHidden are changed depending on which one I pass in.

like image 358
user3648646 Avatar asked Aug 30 '26 07:08

user3648646


1 Answers

Brad's answer is correct, but just in case you wanted something for more general use, so that you can change the value of any scope variable:

<button type="button" ng-click="showDatePicker('IsStartDatePickerHidden')" >

 $scope.showDatePicker = function(varName)
 {
     $scope[varName] = false;
 }

This is not necessarily good practice, but often useful. Speaking of which, you could just do the assignment inside the ng-click:

<button type="button" ng-click="IsStartDatePickerHidden = false" >
like image 137
Constantinos Avatar answered Sep 03 '26 13:09

Constantinos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!