I have a div based on switch but the switch has a boolean variable but the value will be evaluated based on the row.id. Can some one tell me what I am doing wrong here ?
<div ng-switch="hasUrl">
<a ng-switch-when="row.id.indexOf(':') < 0 === true" href="{{url + row.id}}"> <!-- hasUrl = true -->
{{getName(row)}}
</a>
<a ng-switch-default href=".......">
{{getName(row)}}
</a>
</div>
You don't need the ===
, remove it.
<div ng-switch="hasUrl">
<a ng-switch-when="row.id.indexOf(':') < 0" href="{{url + row.id}}"> <!-- hasUrl = true -->
{{getName(row)}}
</a>
<a ng-switch-default href=".......">
{{getName(row)}}
</a>
Be aware that the attribute values to match against cannot be expressions. They are interpreted as literal string values to match against. For example, ng-switch-when="someVal" will match against the string "someVal" not against the value of the expression $scope.someVal.
So according to the docs take following example to solve your case:
<div ng-switch="hasUrl">
<span ng-switch-when="row.id.indexOf(':') < 0"> WONT SHOW </span> <!-- WILL NOT WORK EVER -->
<span ng-switch-when="makeItWork"> ALSO, WONT SHOW</span>
<span ng-switch-when="true">WILL NOT SHOW EITHER</span>
<span ng-switch-when="1">WILL SHOW</span>
</div>
Look carefullyat scope variables and their values:
$scope.hasUrl = 1; /* NOTICE != true BUT 1*/
$scope.row = {};
$scope.row.id = "true:";
$scope.makeItWork = $scope.row.id.indexOf(':') > 0 ? 1 : 0;
console.log($scope.makeItWork); /* SEE THAT TRUE WILL BE LOGGED BUT IT STILL WONT SHOW */
So even though ng-switch
will evaluate an expression, it seems ng-switch-when
wont. If I were you I would just stick to ng-if
instead.
FIDDLE Fixed fiddle
来源:https://stackoverflow.com/questions/41476339/angular-js-dynamic-expression-not-working-for-ng-switch-when