ng-switch + Function

Asked

Viewed 252 times

0

Good afternoon, I’m trying to use the ng-switch to display a value that depends on a condition that is in a function, but I can only pass fixed values to the field, the function with if does not seem to pass the value, if it is not clear, follows the example in codepen.

$scope.value1='0';
  $scope.condition = function(){
    if($scope.value1>=10){
      return $scope.value=200;
    }
  }

http://codepen.io/haykou/pen/zqndw

  • Seems to me a Problemaxy. Could you explain the desired end effect? Click [Edit] and add relevant details if possible.

  • Yes, in the case of the first switch if I type 1 in the input, it will show 1 below and in the second I wanted to create a condition, in the example I would type any number greater than 10 and the div below shows the value 200 <div ng-switch-when="1" >1</div> <div ng-switch-when="condition()" >2</div>

1 answer

0


Translating a part of ng-switch documentation:

Be aware that the attribute values [ng-switch-when] cannot be expressions. Values are interpreted as literals to be compared.

That is, when you use ng-switch-when="condition()", the angle is trying to compare the value of the attribute ng-switch with the string condition() instead of calling the function.

In your case, I would use the ng-show and the ng-Hide to display an alternative condition to ng-switch:

<body ng-app ng-controller='controller'>
    <label>Type a value: <input type="text" ng-model="value" /></label><br />
    <div ng-switch="value" ng-hide="condition()">
        <div ng-switch-when="1">1</div>
        <div ng-switch-when="3">3</div>
        <div ng-switch-when="4">4</div>
        <div ng-switch-when="5">5</div>
        <div ng-switch-default>None</div>
    </div>
    <div ng-show="condition()">2</div>
</body>

It is also possible to do this within the ng-switch-default:

<body ng-app ng-controller='controller'>
    <label>Type a value: <input type="text" ng-model="value" /></label><br />
    <div ng-switch="value">
        <div ng-switch-when="1">1</div>
        <div ng-switch-when="3">3</div>
        <div ng-switch-when="4">4</div>
        <div ng-switch-when="5">5</div>
        <div ng-switch-default>
            <div ng-show="condition()">2</div>
            <div ng-hide="condition()">None</div>
        </div>
    </div>
</body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.