将范围变量传递到ng-click中 [英] Passing scope variable to function in ng-click

查看:61
本文介绍了将范围变量传递到ng-click中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道我必须错过这个问题的javascript的一些基本部分,但无论如何它仍然存在:

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;

我有一个按钮,其ng-click设置为转到我控制器中的一个功能。如果它接受一个可以改变值的参数,这个函数会很好:

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;
 }

当我单步执行此代码时,函数showDatePicker会更改参数的值传入,但似乎没有改变控制器中变量的值,所以没有任何反应。我确信这必须与通过引用传递有关。我只是不确定如何传递这个,以便$ scope.IsStartDatePickerHidden或$ scope.IsEndDatePickerHidden根据我传入的更改。

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.

推荐答案

如何修复 - 示例小提琴: http:/ /jsfiddle.net/p3p6ova7/

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

如果您知道要在作用域上使用的变量,则无需传递这些值。在你的情况下,你正在你的功能中初始化一个新变量, showDatePicker ,并为此赋值为false,这对 $没有任何影响scope.IsStartDatePickerHidden

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

你也可以简单地做 ng-click =IsStartDatePickerHidden = false,但这可能是一些外部最佳实践。

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

这篇关于将范围变量传递到ng-click中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆