2016-10-21 38 views
0

我想將值傳遞給我的指令而不隔離其範圍。指令屬性強制布爾值爲字符串

我的指令有一個鏈接功能來獲取屬性的值:

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

    scope.myAttributeValue = attrs.myAttribute; 

} 

我願做

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

當我傳遞一個布爾值my-attribute,它就會轉變成一個字符串。

如何將布爾值傳遞給my-attribute

+1

您是否嘗試過'my-attribute =「true」'?此外,您的鏈接功能中存在拼寫錯誤(myAtribute缺少t)。你可能需要使用'scope.myAttributeValue = attrs.myAttribute!=='false';'。 –

+0

可能的方法是嘗試添加布爾邏輯來強制它是一個布爾值而不是字符串?例如true == true –

+0

你使用scope.myAttribute綁定了什麼? @,=或者&。檢查你的屬性簽名。如果您使用@,則該值將以字符串形式傳遞。 –

回答

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() method評估字符串作爲Angular 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); 

。希望幫助!