简体   繁体   English

Angular:$ scope.variable上的If-operations

[英]Angular: If-operations on $scope.variable

I want to run a function based on a $scope value. 我想运行一个基于$ scope值的函数。 In my controller, I have: 在我的控制器中,我有:

 $scope.value = "";
 $scope.selector = function(info) { 
    if ($scope.value === "") {
       $scope.value = info;
    } else {
       $scope.value = "";
    }
 }

The function is triggered on ng-click of different images, eg: 按住ng键单击不同的图像时会触发该功能,例如:

<img ng-src="..." ng-click="selector(info)">

My problem is the if-operations dont seem to work on the $scope value. 我的问题是if操作似乎在$ scope值上不起作用。 I have also tried: 我也尝试过:

 $scope.$watch('value', function(val) {
    if(val === "") {
       $scope.value = info;
    }
 }

This works if it is outside a function, but not if I place it in the selector function. 如果它在函数外部,则可以使用,但如果将其放在选择器函数中,则不能使用。 Better approaches always welcome. 总是欢迎有更好的方法。 Thanks for any explanations. 感谢您的任何解释。

You need to pass the parameter from the view to the function, because your function needs an input parameter 您需要将参数从视图传递给函数,因为函数需要输入参数

Change the view as, 将视图更改为

img ng-src="..." ng-click="selector(value)">

Try to enclose your value inside an object. 尝试将您的值包含在对象中。 There are some cases where Angular cannot "see" that the variable changed. 在某些情况下,Angular无法“看到”变量已更改。

So, try to keep something like: 因此,请尝试保留以下内容:

$scope.value = { value: "" };

and change the rest of the code accordingly. 并相应地更改其余代码。

I did a codepen with some fixes in your code and with what I said to you: Running example 我用您的代码中的一些修复以及我对您说的内容做了一个代码笔: 运行示例

In this example you can see the val === "" returning true and false. 在此示例中,您可以看到val ===“”返回true和false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM