[英]How to encapsulate ng-bind-html behavior into custom directive
我想從以下內容中抽象出ng-bind-html行為:
<div ng-repeat="message in messages >
<p ng-bind-html=message.title ng-phone-caller="message.title"> </p>
</div>
並將其移動到我的自定義指令中,該指令接受我的字符串輸入,並將HTML標簽包裹在電話號碼周圍,以便可以在移動設備上點擊。
.directive('ngPhoneCaller',function() {
return {
scope: {
ngPhoneCaller: '='
},
link: function (scope) {
var stringWithHtmlWrapper = $sce.getTrustedHtml(wrapStringWithPhoneNumberHTMLTag(scope.ngPhoneCaller));
scope.ngPhoneCaller = $sce.trustAsHtml(stringWithHtmlWrapper);
}
}
}
});
這樣,使用我的屬性指令ng-phone-caller的任何人都不需要也實例化ng-bind-html。 關於我將如何實現這一目標的任何建議? 我嘗試使用$ sce,但這是否還不要求我使用ng-bind-html? 例如,如果我不將ng-bind-html與$ sce一起使用,則最終得到的消息格式不正確,即:“我們當前不可用。
您是否考慮過為此使用過濾器? 使用$sce.trustAsHtml
將允許您像ng-bind-html
一樣使用HTML。
.filter('phoneCaller', function($sce) {
return function(value) {
return $sce.trustAsHtml(wrapStringWithPhoneNumberHTMLTag(value));
};
});
您可以將此過濾器用作:
<div ng-repeat="message in messages >
<p ng-bind="message.title | phoneCaller"></p>
<!-- Or alternately -->
<p>{{ message.title | phoneCaller }}</p>
</div>
如果您確實不想在客戶端代碼中使用ng-bind-html
,則可以為您的指令提供一個簡單的模板,並在指令控制器中創建一個函數:
angular.module('myapp').directive('ngPhoneCaller', function($sce) {
return {
restrict: 'A',
scope: {
ngPhoneCaller: '='
},
controller: function($scope) {
$scope.wrappedPhoneCaller = function() {
return $sce.trustAsHtml(wrapStringWithPhoneNumberHTMLTag($scope.ngPhoneCaller));
}
},
template: '<p ng-bind-html="wrappedPhoneCaller()"></p>'
};
});
您的客戶端代碼將如下所示:
<div ng-repeat="message in messages >
<div ng-phone-caller="message.title"></div>
</div>
由於此操作是在每個摘要周期中計算的,因此您可能希望對其進行緩存或在控制器中設置自己的$watch
,以將其綁定為常規的$ scope屬性(而不是功能調用)。
使用$sce
:
.directive('ngPhoneCaller',function($sce) {
return {
scope: {
ngPhoneCaller: '='
},
link: function (scope, element) {
var html = wrapStringWithPhoneNumberHTMLTag(scope.ngPhoneCaller);
element.html($sce.getTrustedHtml(html) || '');
}
}
});
您還需要添加$watch
以影響任何范圍更改。
有關更多信息,您可以閱讀原始的ngBindHtml
實現 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.