前言
在實際開發(fā)中,我們難免會遇到接口返回HTML代碼直接綁定到頁面上的情況瞄沙。
- 最簡單的方法就是使用ng-bind-html。
- 使用filter為HTML代碼的添加自定義的內(nèi)容。
- 自定義綁定HTML代碼的directive叹谁,添加點擊事件兴猩。
使用ng-bind-html
- 在ionic1中綁定HTML代碼期吓,最簡單的方法就是使用ng-bind-html。
代碼示例:
<div ng-bind-html="htmlString"></div>
- 有可能綁定上來后某些HTML代碼不會生效倾芝,這時候再加上一個trustAsHtml的filter就好了膘婶。
代碼示例:
.filter('trustedAsHtml', ['$sce', function ($sce) {
return function (htmlCode) {
return $sce.trustAsHtml(htmlCode);
};
}]);
<div ng-bind-html="htmlString|trustedAsHtml"></div>
修改綁定的HTML代碼里面的內(nèi)容
- 復(fù)雜一點的情況,需要綁定的HTML代碼里面的內(nèi)容可能不太符合我們實際開發(fā)時的需求蛀醉。
- 比如說悬襟,img標簽需要添加一些自定義的東西。
- 這個時候就需要我們自己寫正則表達式去匹配內(nèi)容并替換拯刁。
代碼示例:
.filter('myFilter', function () {
return function (content) {
if (typeof content !== 'string') return content;
var re = /(<img\b)([^\>]+>)/gi;
return content.replace(re, "$1" + 'mycontent' + "$2");
}
});
trustedAsHtml filter必須放在最后
<div ng-bind-html="htmlString|myFilter|trustedAsHtml"></div>
為綁定的HTML代碼添加點擊事件
- 更復(fù)雜一點脊岳,為接口返回的HTML代碼添加點擊事件并響應(yīng)。
- 例如垛玻,我們?yōu)榻壎ǖ腍TML代碼里面的img標簽添加點擊事件割捅。
第一步
添加filter,為HTML代碼里的img標簽加上點擊事件的字符串ng-click=picClicked($event)帚桩。
代碼示例:
.filter('picAddEvent', function () {
return function (content) {
if (typeof content !== 'string') return content;
var re = /(<img\b)([^\>]+>)/gi;
return content.replace(re, "$1" + ' ng-click=picClicked($event) ' + "$2");
}
});
第二步
自定義封裝綁定HTML的directive亿驾,響應(yīng)點擊事件,替換原來的ng-bind-html directive账嚎。
代碼示例:
.directive('imcBindHtml', ['$sce', '$parse', '$compile', 'BigImageModalService', function ($sce, $parse, $compile, BigImageModalService) {
return {
restrict: 'E',
link: function ($scope, element, attr) {
angular.element(element).addClass('imc-bind-html');
$scope.$watch(attr.content, function () {
element.html($parse(attr.content)($scope));
$compile(element.contents())($scope);
// 圖片點擊事件
$scope.picClicked = function (event) {
var parent = angular.element(event.target).parent();
if (parent.is('a') && parent.attr('href') !== "") {
// img的父標簽是a且href不為空時莫瞬,點擊圖片時響應(yīng)a標簽的href事件,不響應(yīng)該事件
return;
}
// TODO 響應(yīng)點擊圖片事件操作
};
}, true);
}
}
}]);
第三步
使用imc-bind-html綁定HTML代碼郭蕉。
代碼示例:
<imc-bind-html content="article.mobileContent|picAddEvent"></imc-bind-html>