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

血红的双手。 提交于 2019-12-20 07:39:58

问题


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>

回答1:


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>




回答2:


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

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