2016-06-01 8 views
0

私は、属性がif-login-service="facebook"の要素が作成されるが、この属性には他の値を持つ要素は作成されないようなディレクティブを作成しようとしています。コンテンツを条件付きで作成するangleディレクティブ

私がこれまで

app.directive('ifLoginService', function($compile) { 

    return { 
    restrict: 'EA', 
    compile: function compile(element, attrs) { 

     return function($scope, $element, $attr) { 

     var serviceName = attrs.ifLoginService; 

     if (serviceName === 'facebook') { 

      // use compile to include and compile your content here 
      $compile($element.contents())($scope); 
     } 
     } 
    } 
    }; 
}); 

A Plunker demo下に表示され、このディレクティブで作った進歩がここにあります。それが機能していた場合は、「Facebook」ボタンが表示され、「Facebookではない」ボタンは表示されません。現在、両方のボタンが表示されていますが、どこが間違っているのか分かりません。

+0

[source of ngIf](https://github.com/angular/angular.js/blob/master/src/ng/directive/ngIf.js)を見るか、ngあなたのディレクティブテンプレートに – yoavmatchulsky

+0

@yoavmatchulskyあなたが私のディレクティブテンプレートで 'ng-if'をどのように使用できるかを表示できますか? –

+0

[this](https://gist.github.com/yoavmatchulsky/aed5d49ca26c2f747ccc5632222941fe)のようなものです。ボタン要素はまだ存在することに注意してください。それは理想的ではないので、私はこれを答えとして書いていませんでした。 – yoavmatchulsky

答えて

2

コンパイルサービスを使用してディレクティブを記述する必要があります。

$element[0].html(''); 

やDOMから取り除きます:ここで

$element[0].parentNode.removeChild($element[0]); 

は、あなたのディレクティブが修復される:

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

app.controller('MainCtrl', function($scope) { 
    $scope.model = { 
    toggle: 'true' 
    }; 
}); 

app.directive('ifLoginService', function($compile,$animate) { 

    return { 
    restrict: 'EA', 
    replace: true, 
    compile: function compile(element, attrs) { 

     return function($scope, $element, $attr) { 

     var serviceName = attrs.ifLoginService; 
     console.debug('Testing service name', serviceName); 

     if (serviceName === 'true') { 
      // use compile to include and compile your content here 
      $element.html($compile($element.contents())($scope)); 
     } 
     else 
     { 
      $element[0].parentNode.removeChild($element[0]); 
     } 
     } 
    } 
    }; 
}); 

これを使用するボタンなどのルート要素をクリアする

plunkrへのリンク

+0

私はPlunkerデモをあなたの提案が動作していないようですhttps://plnkr.co/edit/AWTPi5?p=preview –

+0

plunkrを更新しました。リンクを参照してください。 HTMLもまた、model.toggleに基づいて、hide/showディレクティブに変更されました –

関連する問題