将ng-if属性添加到指令中的元素

时间:2015-02-20 05:23:50

标签: javascript html angularjs angularjs-directive

我有一个AngularJS指令,它接受一个I​​D并对此ID进行查找,以获取给定flexbox元素的col-width,hide-state和order。

我想要做的是在元素的hide-state为true时向元素添加ng-if = false属性。有什么办法,我如何在一个指令中添加ng-if属性到一个元素?

我目前的代码:

    .directive("responsiveBehaviour", ['ResponsiveService', function(ResponsiveService){
    var linkFunction = function(scope, element, attributes){
        var id = attributes["responsiveBehaviour"];
        var updateResponsiveProperties = function(){
            element.attr("column-width", ResponsiveService.getWidth(id));
            if(ResponsiveService.getOrder(id)){
                element.attr("order", ResponsiveService.getOrder(id));
            }
            if(ResponsiveService.getHidden(id) == true){
                element.attr("hidden", "");
            } else {
                element.removeAttr("hidden");

            }
        };
        if(id) {
            scope.$watch('device', function () {
                updateResponsiveProperties();
            });
        }
    };

如果我添加

element.attr("ng-if", false);

而不是

element.attr("hidden", "");

它只是将ng-if属性呈现给元素但没有动作发生,因此尽管ng-if为false,元素仍然呈现并可见。

你对如何实现我想要的东西有任何想法吗?

提前致谢。

迎接

1 个答案:

答案 0 :(得分:0)

如下所示:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

app.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    scope: { text: '@' },
    template: '<p ng-click="add()">Jenish</p>',
    controller: function ( $scope, $element ) {
      $scope.add = function () {
        var el = $compile( "<test text='n'></test>" )( $scope );
        $element.parent().append( el );
      };
    }
  };
});

工作插件是here

<强>更新

以下是您要求的简单示例。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.add = function () {
    alert('Jenish');
    $scope.cond = false;
  }
  $scope.cond = true;
});

app.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    
    template: '<p ng-click="add()">Click me to hide</p>',
    link: function ( $scope, $element, attr ) {
      
      var child = $element.children().attr('ng-if', 'cond') 
      console.log($element)
      $compile(child)($scope);
    }
     
  };
});
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <test></test>
  </body>

</html>

我希望这会对你有所帮助。