Angular js : Dynamic expression not working for ng-switch-when

醉酒当歌 提交于 2019-12-02 13:10:52

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!