Passing scope variable to ng-click

So, I know that I must be missing some basic javascript with this quesiton, but here it is anyway:

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

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

      

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

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

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

      

when I go through this code the showDatePicker function changes the value of the passed parameter, but doesn't seem to change the value of the variable in the controller, so nothing happens. I'm sure it must be related to passing by reference. I'm just not sure how to pass this so that the $ scope.IsStartDatePickerHidden or $ scope.IsEndDatePickerHidden variables change depending on which pass I am in.

+3


source to share


2 answers


How to fix-this-example Fiddle: http://jsfiddle.net/p3p6ova7/

If you know the variables you want to work with in your scope, there is no need to pass those values. In your case, you initialized a new variable in your functon, showDatePicker

and assigned false to this, which would not affect$scope.IsStartDatePickerHidden



You can also just do it ng-click="IsStartDatePickerHidden = false"

, but that might be a little outside of best practice.

+2


source


Brad's answer is correct, but just in case you need something more general so 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 it is often helpful. Speaking of which, you can simply do the assignment inside ng-click:

<button type="button" ng-click="IsStartDatePickerHidden = false" >

      

+6


source







All Articles