2016-10-21 7 views
0

スコープを分離せずにmyディレクティブに値を渡したいとします。ディレクティブ属性はブール値を文字列に強制します

私のディレクティブは、属性の値を取得するためのリンク機能を持っています

link: function(scope, element, attrs, ctrl) { 

    scope.myAttributeValue = attrs.myAttribute; 

} 

私はmy-attributeにブール値を渡すと、それが変換される

<directive my-attribute="{{true}}"></directive> 

をやりたいです文字列。

ブール値をmy-attributeに渡すにはどうすればよいですか?

+1

あなたはちょうど 'my-attribute =" true "'を試しましたか?また、リンク関数のスペルミスがあります(myAtributeにはtがありません)。 'scope.myAttributeValue = attrs.myAttribute!== 'false';'を使う必要があるかもしれません。 –

+0

考えられる方法はブール論理を追加して文字列ではなくブール値にすることです。例えばtrue == true –

+0

scope.myAttributeにはどのバインディングを使用していますか? @、=、または。あなたの属性の署名をチェックインしてください。 @を使用している場合、値はStringとして渡されます。 –

答えて

1

使用scope.$eval

app.directive("myDirective", function(){ 
    return function linkFn(scope,elem,attrs) { 
     var x = scope.$eval(attrs.myDirective); 
     console.log(x); 
     console.log(typeof x); 
    } 
}); 

HTML

<div ng-app="myApp"> 
    <p my-directive="true"></p> 
</div> 

$eval() methodAngular Expressionとして文字列を評価し、タイプを保持します。

角度式を文字列に変換するので、補間(二重中括弧{{true}})を使用しないでください。詳細については

、ブール値で値を比較するAngularJS $rootScope.Scope API Reference --$eval

DEMO on JSFiddle

0

てみブールに変換されます参照してください。

scope.myAttributeValue = attrs.myAttribute == true; 

console.log(typeof scope.myAttributeValue); 
console.log(scope.myAttributeValue); 

exempleについて

願って助けて!

関連する問題