AngularJS参考变量基于另一个变量

时间:2017-08-25 08:54:54

标签: javascript angularjs angularjs-scope

我希望能够在Angular模板中引用一个变量,该模板是在带有过滤器的另一个变量上构建的。

例如,我可能在控制器中有这个:

$ scope.EuropaLeague = true;

如果我在模板中执行此操作,它将按预期工作:

<div ng-if="EuropaLeague">

</div>

但是如果我想动态填充ng-if来自ng-repeat的东西,例如

{{item.leagueName | myFilter}}

所以上面会引用我的范围变量$ scope.EuropaLeague例如。对错吗?

由于

1 个答案:

答案 0 :(得分:2)

这是工作代码:

&#13;
&#13;
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.leagues =
  [
    {
      "id": 1,
      "name": "ChampionsLeague",
    },
    {
      "id": 2,
      "name": "EuropaLeague",
    },
    {
      "id": 3,
      "name": "FACup",
    }
  ]
  $scope.obj = {};
  $scope.obj['EuropaLeague'] = false;
  $scope.obj['FACup'] = false;
  $scope.obj['ChampionsLeague'] = true;
  
});
&#13;
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <ul ng-repeat="item in leagues" ng-if="item.name">
      <li ng-if="obj[item.name]">{{item.name}}</li>
    </ul>
  </body>

</html>
&#13;
&#13;
&#13;