Javascript 如何将ng bind html行为封装到自定义指令中
我想从以下内容中抽象出ng绑定html行为:Javascript 如何将ng bind html行为封装到自定义指令中,javascript,html,angularjs,Javascript,Html,Angularjs,我想从以下内容中抽象出ng绑定html行为: <div ng-repeat="message in messages > <p ng-bind-html=message.title ng-phone-caller="message.title"> </p> </div> 因此,任何使用我的属性指令ng phone caller的人都不需要同时实例化ng bind html。关于如何实现这一点,有什么建议吗?我尝试使用$s
<div ng-repeat="message in messages >
<p ng-bind-html=message.title ng-phone-caller="message.title"> </p>
</div>
因此,任何使用我的属性指令ng phone caller的人都不需要同时实例化ng bind html。关于如何实现这一点,有什么建议吗?我尝试使用$sce,但这不需要我使用ng绑定html吗?例如,如果我没有将ng bind html与$sce一起使用,我会得到一条格式不正确的消息,即“我们当前不可用。”
.directive('ngPhoneCaller',function($sce) {
return {
scope: {
ngPhoneCaller: '='
},
link: function (scope, element) {
var html = wrapStringWithPhoneNumberHTMLTag(scope.ngPhoneCaller);
element.html($sce.getTrustedHtml(html) || '');
}
}
});
您还需要添加
$watch
以影响任何范围更改
有关的更多信息,请阅读原文
ngBindHtml
您是否考虑过为此使用筛选器?使用$sce.trustAsHtml
将允许您像ngBindHtml
一样使用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>
然后,您的客户端代码将如下所示:
<div ng-repeat="message in messages >
<div ng-phone-caller="message.title"></div>
</div>
为什么不在指令中使用模板
来包装它呢?是范围.ngPhoneCaller
只是文本字符串?还是html?如果是字符串,当angular可以为你做的时候,你正在做的是过度的。它是一个字符串,一旦传递到ng phone caller d中,它将被更新为在电话号码周围有一个href标记directive.Using$sce仍然需要我使用ng bind html,对吗?请查看我更新的PostError。ng bind html
使用它,您的指令也使用它。独立使用。查看@doxavore answer。筛选器是您任务的最佳解决方案。因为它关心任何源数据更改。我使用过,但仍坚持使用指令be因为它包括DOM操作。据我所知,$sce.trustAsHtml只会使您的html安全使用,但在视图中,如果我这样做了{{message.title | phoneCaller}它将呈现字符串文字。我仍然需要添加ng bind html属性以正确显示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>