简体   繁体   中英

Angular: If-operations on $scope.variable

I want to run a function based on a $scope value. 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:

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

My problem is the if-operations dont seem to work on the $scope value. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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