3

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.

0

2 Answers 2

6

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" >
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting I never thought of $scope as a key value collection but it makes perfect sense.
This is exactly what I was looking for. Solved a problem that took about 2 days of my time. Thanks for sharing.
2

The how-to-fix-that-example Fiddle: http://jsfiddle.net/p3p6ova7/

If you know the variables you want to work with on your scope, there is no need to pass in those values. In your case, you were initializing a new variable within your functon, showDatePicker, and assigning false to that, which wouldn't have any effect on $scope.IsStartDatePickerHidden

You could also simply do ng-click="IsStartDatePickerHidden = false", but that may be a little outside best practice.

2 Comments

I have other things I need to do inside the function or I would just do it inline.
Then use multiple functions or ng-click="showDatePicker('IsStartDatePickerHidden') and $scope.showDatePicker(name) { $scope[name] = false; } as Constantinos suggested.

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.