观察角度中的Html属性更改

时间:2015-10-13 15:58:40

标签: javascript html angularjs

我正在制作自举手风琴并有3个部分。我需要根据html属性更改来更改类。有什么方法可以检查“咏叹调”扩展'属性值并适用于ng-class

<a class="collapsed" aria-expanded="true" >
    My Open Tasks <i class="fa fa-sort-asc pull-right" ng-class="aria-expanded? 'fa-sort-desc' : 'fa-sort-asc'"></i>
</a>
<a class="collapsed" aria-expanded="false" >
    My Open Tasks 2 <i class="fa fa-sort-asc pull-right" ng-class="aria-expanded? 'fa-sort-desc' : 'fa-sort-asc'"></i>
</a>
<a class="collapsed" aria-expanded="false" >
    My Open Tasks 3 <i class="fa fa-sort-asc pull-right" ng-class="aria-expanded? 'fa-sort-desc' : 'fa-sort-asc'"></i>
</a>

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个。它是一个自定义指令,当您将其添加到元素时,将检查元素并观察它的指令。

angular.directive("ariaCheck", function(){
        return {
           restrict: "A",
           link: function(scope, element, attributes){
                      scope.$watch(function() {return element.attr('aria-expanded'); }, function(){
                      if(attributes.ariaExpanded){
                          element.addClass("some-class");
                       }
                    }
                 }   
           }
});

然后在你的html中添加指令......

<a aria-check class="collapsed"  role="button" data-toggle="collapse" data-parent="#accordion" href="#myopentasks" aria-expanded="true" aria-controls="collapseOne" >
                    My Open Tasks <i class="fa fa-sort-asc pull-right" ng-class="aria-expanded? 'fa-sort-desc' : 'fa-sort-asc'"></i>
                </a>

答案 1 :(得分:0)

实现它的角度方法是在该属性上使用双向绑定:

angular.directive("ariaCheck", function () {
  return {
      restrict: "A",
      scope: {
         ariaExpanded: "="
      },
      link: function (scope) {
          //some logic to set ariaExpanded to false
          scope.ariaExpanded = false;
      }
  }
});

标记:

  <a class="collapsed" aria-expanded="true" >
    My Open Tasks 
    <i class="fa fa-sort-asc pull-right" ng-class="{'fa-sort-desc': ariaExpanded, 'fa-sort-asc': !ariaExpanded}"></i>                        
  </a>

确保ariaExpanded是:在指令的逻辑内改变。 如果您需要倾听外部世界的变化,可能需要更复杂的解决方案。