最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to apply directive conditionally in AngularJS? - Stack Overflow

programmeradmin3浏览0评论

I want to apply a simple directive conditionally using ngAttr. I don't understand why my directive is always displayed. So if I have an undefined / false variable I want to apply my directive: dirr.

When using ngAttr, the allOrNothing flag of $interpolate is used, so if any expression in the interpolated string results in undefined, the attribute is removed and not added to the element.

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;
 }])
; 

I want to apply a simple directive conditionally using ngAttr. I don't understand why my directive is always displayed. So if I have an undefined / false variable I want to apply my directive: dirr.

When using ngAttr, the allOrNothing flag of $interpolate is used, so if any expression in the interpolated string results in undefined, the attribute is removed and not added to the element.

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;
 }])
; 
Share Improve this question edited Feb 25, 2016 at 9:21 que1326 asked Feb 25, 2016 at 9:05 que1326que1326 2,3254 gold badges43 silver badges59 bronze badges 4
  • 2 FYI you should avoid naming your own variables, directives etc under the ng namespace ($scope.ngVar). Thats for core angular ponents and could cause confusion for future developers. – ste2425 Commented Feb 25, 2016 at 9:12
  • @ste2425 it's a fast example, please be on topic !! – que1326 Commented Feb 25, 2016 at 9:14
  • 2 He says "FYI" as side note, not "I am on the topic"! – asdf_enel_hak Commented Feb 25, 2016 at 9:16
  • @asdf_enel_hak, ste2425 ok, I changed the variable name. – que1326 Commented Feb 25, 2016 at 9:21
Add a ment  | 

3 Answers 3

Reset to default 4

You can make use of AngularJS's inbuilt directive ng-if to check for the condition and execute it conditionally.

Example:

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

Form documentation

All of the Angular-provided directives match attribute name, tag name, ments, or class name

so whenever angular matches a diretive with attribute name,it piles the template and renders the html irrespective of attribute value.

anyway you can use scope in directive template.so use ng-hide with scope's hidden property

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;
 }]);

The answers are true and the sample code you provided works for small issues, but when it es resolving this problem on large applications you may want to take this approach:

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;
})

This is more tidy and you may not want to duplicate your code using ngIf or ngSwitch directives in seperate divs when you have something like:

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

评论列表(0)

  1. 暂无评论