用角突出显示单词 [英] Highlighting words with angular

查看:48
本文介绍了用角突出显示单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许用户单击特定div中的单词,并且该单词将突出显示.我很新,并且知道,我所做的工作还差得很远,但是我看了很多视频,读了很多文章,被困住了.即使我没有确切地知道该怎么做,我下一步的任何方向也将非常有用.

I am trying to allow the user to click on a word in a particular div and that word will be highlighted. I am very new and know that what I have made is not close to working, but I have watched lots of videos and read lots of articles and am stuck. Even if I don't get an answer of exactly what to do, any direction for my next step would be incredibly helpful.

我想我需要一条指令,该指令将div,分割文本并在每个单词周围添加一个跨度.此div需要一个突出显示单词的click事件.我经历了很多次迭代,每时每刻都被封锁.

I think I need a directive that would take the div, divide up the text and add a span around each word. This div needs a click event that highlights the word. I have gone through lots of iterations and I am getting blocked at every point.

我在页面上还有很多其他的内置指令,因此我知道我的应用程序总体上设置正确,并且我将指令包含在app模块中.

I have plenty of other angular built in directives working on the page, so I know that I have the app in general set up correctly, and I am including the directive in the app module.

<div my-prepare-text ng-bind-html="item.text | unsafe"></div>

angular.module('MyDirectives', [])
  .directive('myPrepareText', function() {
return {
  restrict: 'A',
  link: function(scope, element) {
    var words = element.text().split(' ');
    var text = words.join("</span> <span my-highlight ng-click='highlight()'>");
    element.html("<p><span my-highlight ng-click='highlight()'>" + text + "</span></p>");
  };
};
  })

推荐答案

您可以创建一个指令,将字作为属性,然后使用ng-repeat来创建跨度.

You can create a directive that gets the words as an attribute and then uses ng-repeat to create the spans.

我做了一个基本示例,以显示此行为.

I made an basic example to show this behavior.

angular.module('MyDirectives', [])
  .directive('myPrepareText', function() {
    return {
      restrict: 'A',
      template: '<div><span ng-repeat="word in words" class="single-word" ng-click="highlight($event)">{{word}}</span></div>',
      link: function($scope, $element) {
        $scope.words = $element.attr('words').split(' ');
        $scope.highlight = function(event) {
          angular.element(event.target).toggleClass('highlight');
        };
      }
    };
  });

.highlight {
  background-color: yellow;
}
.single-word::after {
  content: ' ';
  background-color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<!DOCTYPE html>
<html>

<head>
</head>

<body ng-app="MyDirectives">
  <div words="so many words to highlight" my-prepare-text></div>
</body>

</html>

这篇关于用角突出显示单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆