2017-02-21 63 views
1

我使用的是AngularJS,目前我只能突出顯示文本中的單個單詞。但我想用多種顏色突出顯示多個單詞。使用AngularJS過濾器突出顯示多個單詞

使用從網絡調用此迴應:

{ 
    "text" : "This is a long wall of text of which contains multiple words that I want to highlight using multiple colors", 
    "word1" : "wall", 
    "word2" : "words", 
    "word3" : "colors" 
} 

我要顯示這樣的文字:

results

+2

你可以改變數據結構或者是外部終點? 如果你可以改變或適應數據結構,你可以做這樣的事情[JsFiddle,我剛剛創建...](http://jsfiddle.net/j28kmq42/14/) –

+1

@ The.Bear我可能要求改變,但我不確定是否有可能。無論如何,謝謝你的例子。我會根據它來修補,看看我能否找到方法。真的很感謝你幫助我的時間! –

回答

1

以下是在保持數據結構的同時執行此操作的一種方法。

angular.module('myApp', []) 
 
    .controller('myCtrl', function($scope) { 
 
    $scope.response = { 
 
     "text": "This is a long wall of text of which contains multiple words that I want to highlight using multiple colors", 
 
     "word1": "wall", 
 
     "word2": "words", 
 
     "word3": "colors" 
 
    }; 
 
    }) 
 
    .directive('highlight', function() { 
 
    return { 
 
     restrict: 'E', 
 
     scope: { 
 
     data: '=' 
 
     }, 
 
     link: function(scope, element, attrs) { 
 
     let text = scope.data.text; 
 
     delete scope.data.text; 
 
     let words = Object.values(scope.data); 
 

 
     element.html(text.split(" ").map(function(w) { 
 
      let index = words.indexOf(w); 
 
      return index !== -1 ? '<span class="word' + (index + 1) + '">' + w + '</span>' : w; 
 
     }).join(" ")); 
 
     } 
 
    }; 
 
    });
.word1 { 
 
    background-color: yellow; 
 
} 
 

 
.word2 { 
 
    background-color: green; 
 
} 
 

 
.word3 { 
 
    background-color: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    <highlight data="response"></highlight> 
 
</div>

+0

無論如何,我可以使用CSS手動設置顏色。例如'.word1 {0}背景顏色:黃色; } .word2 {background_color:green; } .word3 {background_color:blue; background-color:blue; }' –

+0

我最終改變了@ The.Bear提供的響應格式和修改過的代碼示例,但是這實際上回答了這個問題。 :) –

1

這裏是做熊的工作fiddle的其他方式!

function myCtrl($scope) { 
$scope.item = { 
text: "I am a Bear in the forest. We are two bears climbing a tree.", 
search: [{ 
    text: "Bear", 
    color: "brown" 
}, { 
    text: "forest", 
    color: "green" 
}, { 
    text: "tree", 
    color: "orange" 
}] 
}; 
} 

var app = angular.module('myApp', ['highlightDirective']); 
app.controller('myCtrl', ['$scope', myCtrl]); 

function highlight() { 

var directive = { 
restrict: 'E', 
scope: { 
    text: '=', 
    search: '=' 
}, 
link: function link(scope, $element, attr) { 

var text = scope.text; 
var search = scope.search; 

for (var i = 0; i < search.length; i++) { 
    var s = search[i]; 
    var html = '<span class="highlightText ' + s.color + '">$&</span>'; 

    text = text.replace(new RegExp("\\b" + s.text + "\\b"), html); 
} 

    $element.html(text); 
    } 
    }; 
    return directive; 
} 

var highlightDirectiveModule = angular.module("highlightDirective", []); 
highlightDirectiveModule.directive('highlight', highlight); 
相關問題