[英]Integrating Angularjs directives and 3rd party widgets
我正在嘗試建立一個將封裝第三方庫的指令。 我的指令可能如下所示:
angular.module('MyApp').directive("shareButton", [function() {
return {
link: function($scope, elem, attrs ) {
stWidget.addEntry({
"service": attrs.service,
"element": elem[0],
"url": attrs.shareUrl,
"title": attrs.shareTitle,
"type": attrs.type || "chicklet",
"text": attrs.displayText || "",
"image": attrs.shareImage
});
}
};
}
使用可能如下所示:
<a href="#" share-button
type="chicklet"
service="facebook"
share-url="{{shareUrl}}"
share-title="{{shareTitle}}"
share-image="{{shareImage}}"></a>
問題是當您使用{{ someValue }}
綁定時出現的。 在偽指令上調用link方法期間,這些值將作為null傳遞。 要獲得這些值,您必須使用attrs.$observe()
。 問題是我正在使用的第三方庫在調用stWidth.addEntry()
之后,使用絕對零方式來修改這些值。 我已經做了很多分析他們的代碼,並且他們使用閉包和局部變量來確保我不能更改這些值。
因此,除了重寫它之外,我對第三方庫無能為力,所以我的問題是我可以用Angular做什么來延遲調用該stWidget.addEntry()
方法,直到獲得所有值。 還是有某種綁定形式不需要使用attrs.$observe()
方法?
我不在乎綁定更改。 在這種情況下,簡單的一次綁定就足夠了。
使用$timeout
應該可以解決問題
angular.module('MyApp').directive("shareButton", [function($timeout) {
return {
link: function($scope, elem, attrs ) {
$timeout(function(){
stWidget.addEntry({....
},0);
});
您可以使用范圍的$ eval方法根據鏈接函數內的$scope
評估屬性:
HTML:
<a href="#" share-button type="chicklet" service="facebook" share-url="shareUrl"
share-title="shareTitle" share-image="shareImage">
指令鏈接功能:
link: function ($scope, elem, attrs) {
console.log($scope.$eval(attrs.shareUrl),
$scope.$eval(attrs.shareTitle),
$scope.$eval(attrs.shareImage))
stWidget.addEntry({
"service": attrs.service,
"element": elem[0],
"url": $scope.$eval(attrs.shareUrl),
...
我認為您需要在鏈接函數中使用attrs。$ observe。
請參閱http://docs.angularjs.org/guide/directive#Attributes上的角度指令文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.