【问题标题】:Adding multiple expressions using ng-class in AngularJS在 AngularJS 中使用 ng-class 添加多个表达式
【发布时间】:2014-08-19 19:39:25
【问题描述】:

当路径为http://localhost/#/http://localhost/#/main/ 时,我尝试设置类.active,因为这两个路径是同一页。

为什么ng-class="{'class1' : expression1, 'class1' : expression2}" 不起作用?

控制器

angular.module('testApp')
  .controller('NavmenuCtrl', function ($scope, $location) {
  $scope.isActive = function (providedPath) {
    return providedPath === $location.path();
  };
});

部分视图

<li ng-class="{ active: isActive('/'), active: isActive('/main/')}">
  <a href="#/">Home</a>
</li>

相关链接

Adding multiple class using ng-class

AngularJS ng-class multiple conditions

Oliver Tupman: Keep CSS classes out of your Angular controllers

Scotch.io: the many ways to use ng-class

【问题讨论】:

  • ng-class="{ active: isActive('/') || isActive('/main/')}" ?您是否检查了$location.path() 是否符合您的预期?
  • 它适用于一条路径而不适用于另一条路径吗?您也可以为类的一个实例使用 or 运算符编写它。 { 活动:条件1 ||条件2}
  • 尝试将console.log("provided: " + providedPath + " location: " + $location.path()); 插入到您的 isActive 方法中。然后,您可以在控制台中看到正在与什么进行比较,这通常可以指出问题。
  • 它不起作用,因为 angular 将参数评估为一个对象,并且在您的示例中,属性 class1 是重复的。
  • @fiskers7 是的,我的原始代码仅适用于第二个 URL 路径。

标签: angularjs ng-class


【解决方案1】:

让我的评论成为答案,是的,您的问题在于重复键,您可以这样做:-

ng-class="{ active: isActive('/') || isActive('/main/')}"

或者可能更好:-

让你的isActive 类接受多个参数:-

$scope.isActive = function () {
    //Look for a match in the arguments array
    return [].indexOf.call(arguments, location.path()) > -1;
};

并将其用作:-

ng-class="{ active: isActive('/', '/main/')}"

Shim support for indexOf for older browsers

【讨论】:

  • 为在我面前得到你的答案投赞成票!
  • @fiskers7 你能把你的评论作为答案,这样我至少可以投票吗?
【解决方案2】:

晚了一天,但希望值得。

您也可以为类的一个实例使用 or 运算符来编写它。

ng-class="{ 'active': condition1 || condition2 }"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2013-09-23
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多