Ng-class if scope value equals attribute value of element clicked

时间:2016-04-04 17:35:29

标签: javascript angularjs

How can I write a ng-class function that adds the class "active" only if the scope value of "selectedFilter" == the value of the "type" attribute?

HTML:

<li ng-click="selectFilter($event)" ng-class="{'active': selectedFilter == $element.type}" type="portfolio">PORTFOLIO</li>

Directive function:

link: function(scope, el, attr) {
        scope.selectFilter = function(filterChosen){
            var selectedFilterValue =  filterChosen.target.attributes.type.value;
            scope.selectedFilter = selectedFilterValue;
        };
    }

1 个答案:

答案 0 :(得分:0)

我不确定是否有很好的方法可以将DOM上下文传递给作用域上的函数,而无需像ng-click那样访问$event。您也可以放弃使用ng-class,只需通过访问ng-click函数中的元素手动分配类。

类似的东西:

 for (var i = 0; i < element[0].children.length; i++) {
      if (element[0].children[i].type == scope.selectedFilter) {
        element[0].children[i].className = 'active'
      } else {
        element[0].children[i].className = ''
      }
    }