[英]AngularJS: Display part of an expression in bold
我的目標是使角度表達的一部分變得大膽。
所以基本上我正在使用對象obj
,並將其轉換為字符串str
。
obj = $scope.gridOptions1.api.getFilterModel();
for (var propt in obj) {
str += (" " + propt + ': ' + obj[propt]);
}
然后我需要在該對象中找到一個特定的單詞,例如“Depot”。 我正在使用str.indexOf("Depot")
這樣做。 我把它設置為變量d
:
for (i = 0; i < str.length; i++) {
var d = str.indexOf("Depot");
}
然后我用一個BOLD“Depot”替換ORIGINAL“Depot”:
if (d !== -1 ) {
var depot = str.substring(d, d + 5);
finalString = str.replace(depot, depot.bold());
}
然后我將我的字符串發射到范圍上:
$scope.getFiltered = finalString;
.bold()方法只是在我的UI中返回帶有“Depot”周圍的粗體標記的字符串。
所以我認為字符串不被認為是HTML,還有其他方法嗎?
你需要告訴angular將結果視為html。 為此,您需要將ngSanitize作為模塊依賴項包含在內,並使用ng-bind-html插入結果。
所以html看起來像
<p ng-bind-html="htmlString"></p>
和角部分
angular.module('app', ['ngSanitize'])
使用ng-bind-html將字符串呈現為html內容。 在您的情況下,請在HTML頁面上使用以下內容:
<p ng-bind-html="getFiltered"></p>
我會這樣試過的,
var myApp = angular.module('myApp',[]); myApp.directive('wrapInTag', function() { return { restrict: 'A', link: function(scope, elm, attr) { var tag = attr.tag || 'strong'; var words = eval(attr.words) || []; var text = scope.myText; for(var i=0; i< words.length; i++) { text = text.replace(words[i],'<'+tag+'>'+words[i]+'</'+tag+'>'); } elm.html(text); } } }); myApp.controller('MyCtrl', ['$scope', function ($scope) { $scope.myText = 'Hello, Here you will find your word in bold'; $scope.words = ['Hello','your','bold']; }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> <bod ng-app="myApp"> <div ng-controller="MyCtrl"> <div wrap-in-tag words="{{words}}">{{myText}}! </div> </div> </body>
你應該使用$sce
服務:
JS:
$scope.getFiltered = '<strong>render me as HTML</strong>';
$scope.trustedHtml = $sce.trustAsHtml($scope.getFiltered);
HTML:
{{trustedHtml}}
我在自定義過濾器的幫助下實現了這一點。
我可以分享我的方法。 您可以使用此代碼或使用邏輯。
$scope.data = [
{ value: "1", bold: false },
{ value: "2", bold: false },
{ value: "3", bold: false },
{ value: "4", bold: false },
{ value: "5", bold: false },
{ value: "6", bold: false }
];
這是我的數據。 實際上我想在1,2,3,4等中顯示和搜索。為此,我為每個值添加了一個屬性, bold
。
這是我的html相同,
<input type="text" ng-model="search" />
<p ng-repeat="a in data | myFilter : search">
<b ng-show="a.bold"> {{a.value}} </b>
<span ng-hide="a.bold">{{a.value}}</span>
</p>
這是我的自定義過濾器,
app.filter("myFilter", function () {
return function (input, search) {
angular.forEach(input, function (value, index) {
if ( value.value == search) {
value.bold = true;
}
else
{
value.bold = false;
}
});
return input;
};
});
希望這對你有所幫助。
快樂的編碼。 :)
我做到這一點的目的是通過我的刺痛並首先檢查我想要改變的單詞是否存在,如果不是,我只是按原樣傳遞字符串。 一旦我知道這個詞在那里,我就用粗體替換同一個詞。
$scope.makeBold = function(item) {
if(item.indexOf("LookForMe") != -1)
{
b = "LookForMe";
var d = item.replace(b,b.bold());
return '<div>'+d+'</div>';
}
else {
return '<div>'+item+'</div>';
}
};
我的控制器看起來像這樣:
var app = angular.module('myApp', ['ngSanitize'],function(){});
在HTML中:
<div ng-bind-html="makeBold(stringToChange)"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.