【问题标题】:data-ng-class conditions is not working when changing url manually手动更改 url 时 data-ng-class 条件不起作用
【发布时间】:2016-07-22 12:38:44
【问题描述】:

我在 data-ng-class 上的 div 上做了一个条件语句,我想以某种方式将此范围添加到控制器并指定 url 何时为 /vegetarian 以应用类“egg”,我手动更改我想要的 url要应用“培根”类,但它不起作用,我哪里出错了?

html:

<div data-ng-class="{'egg': isVeggie, 'bacon': !isVeggie }">
  Text here
</div>

控制器:

app.controller('foodCtrl', function ($scope, $location) {

  $scope.location = $location;
  $scope.isVeggie = false;


  $scope.isVeggie = function() {
    if(isVeggie === $location.path('/vegetarian')) {
      return true;
    }
  }

});

这不起作用。当我输入 /vegetarian 时,正在应用鸡蛋类,但是当我将 url 更改为 /breakfast 之类的其他内容时,“鸡蛋”类仍然存在。我怎样才能使这项工作? 谢谢

【问题讨论】:

    标签: angularjs url controller ng-class route-provider


    【解决方案1】:

    为什么属性和函数同名?毕竟你将只有功能

    $scope.isVeggie = false;
    
    $scope.isVeggie = function() {
        if(isVeggie === $location.path('/vegetarian')) {
           return true;
        }
    }
    

    将您的代码更改为仅具有该功能。

    仅限

    $scope.isVeggie = function() {
            if(isVeggie === $location.path('/vegetarian')) {
               return true;
            }
        }
    

    和标记

    <div data-ng-class="{'egg': isVeggie(), 'bacon': !isVeggie() }">
      Text here
    </div>
    

    【讨论】:

      【解决方案2】:

      您将 ng-class 指令绑定到属性 isVeggie 而不是函数 isVeggie()。

      将您的 html 更改为:

      <div data-ng-class="{'egg': isVeggie(), 'bacon': !isVeggie() }">
        Text here
      </div>
      

      然后您可以在控制器中删除以下行:

      $scope.isVeggie = false;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-27
        • 1970-01-01
        • 2014-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-19
        相关资源
        最近更新 更多