如何在AngularJS中有条件地应用指令?

时间:2016-02-25 09:05:54

标签: javascript angularjs angularjs-directive

我想使用 ngAttr 有条件地应用一个简单的指令。我不明白为什么我的指令总是显示出来。因此,如果我有 undefined / false 变量,我想应用我的指令: dirr

  

使用 ngAttr 时,会使用 $ interpolate allOrNothing 标记,因此如果插值字符串中的任何表达式导致未定义,该属性将被删除,不会添加到元素中。

My code pen

<div ng-app="myApp" ng-controller="MainController" class="container-fluid">
    <h2 ng-bind="currentVersion"></h2>
    <hr>
    <div ng-attr-dirr="hidden || undefined">Default div</div>
</div>

angular.module('myApp',[])
 .directive('dirr', function(){
   return {
     restrict:'AE',
     template:'<div>Div from directive</div>'
   }
 })
 .controller('MainController',['$scope', function($scope){
   $scope.currentVersion = 'Angular 1.3.6';
   $scope.hidden = undefined;
 }])
; 

3 个答案:

答案 0 :(得分:4)

您可以使用AngularJS的内置指令ng-if来检查条件并有条件地执行它。

示例:

<div ng-if="{some_condition}">
    <dirr></dirr> <!--Execute the directive on the basis of outcome of the if condition-->
</div>

答案 1 :(得分:1)

表格文件

  

所有Angular提供的指令都匹配属性名称,标记名称,注释或类名

因此,只要angular匹配带有属性名称的diretive,它就会编译模板并呈现html而不管属性值。

无论如何,你可以在指令模板中使用范围。所以使用ng-hide和范围的隐藏属性

angular.module( '对myApp',[])

 .directive('dirr',function(){
     return{
        restrict:'AE',
        template:'<div ng-hide="hidden">Div from directive</div>',
     }
 })
 .controller('MainController',['$scope', function($scope){
     $scope.hidden=false;
 }]);

答案 2 :(得分:0)

答案是正确的,您提供的示例代码适用于小问题,但是当它解决大型应用程序上的此问题时,您可能希望采用这种方法:

Updated Pen

<div ng-app="myApp" ng-controller="MainController" class="container-fluid">
    <h2 ng-bind="currentVersion"></h2>
    <hr>
    <div dirr value="{{hidden}}">Default div</div>
  </div>

.directive('dirr', function($log){
  var directiveInstance =  {
    restrict:'AE',
    scope:{
      value:'@'
    },
    link: function (scope, element, attrs, ctrl) {
      if(attrs.value === 'true'){
        console.log('directive on !!');
        $log.debug('element',element);
        element[0].innerHTML = '<div>hello ' + attrs.value + '</div>';
      }
      else {
        console.log('directive off !!');
      }
    }
  }
  return directiveInstance;
})

这样更整洁,如果你有类似的话,你可能不想在单独的div中使用 ngIf ngSwitch 指令复制代码:

<table>
  <thead dirr value="{{statement}}">
    <tr>
     <th>
        CrazyStuffHere...
     </th>
     <th>
        CrazyStuffHere...
     </th>
     ....
    </tr>
  </thead>
</table>