javascript - 如何使用 AngularJS 获取光标下的单词?

标签 javascript jquery html angularjs

我需要在我的应用程序中使用 angularJS 获得此功能,以便每个单词在光标移动到它上方时显示吗? 问题是该段落是由 ng-bind 动态生成的,我需要通过移动悬停来查看每个单词

<p>Each word will be wrapped in a span.</p>
<p ng-bind="myparagraph"></p>
Word: <span id="word"></span>

    $('p').each(function() {
        var $this = $(this);
        $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
    });
     // bind to each span
    $('p span').hover(
        function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
        function() { $('#word').text(''); $(this).css('background-color',''); }
    );

http://jsfiddle.net/5gyRx/

最佳答案

使用指令:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.model = {
    word: "",
    paragraph1: "Each word will be wrapped in a span.",
    paragraph2: "A second paragraph here."
  };
});


app.directive('wordUnderCursor', function() {
  return {
    scope: {
      wordUnderCursor: "=",
      wordUnderCursorContent: "="
    },
    link: function(scope, elment) {

      scope.$watch('wordUnderCursorContent', function(newValue) {
        console.log(newValue);
        if (newValue) {
          var $element = $(elment);

          $element.html(newValue.replace(/\b(\w+)\b/g, "<span>$1</span>"));

          $element.find('span').hover(
            function() {
              var $span = $(this);
              $span.css('background-color', '#ffff66');
              scope.$apply(function() {
                scope.wordUnderCursor = $span.text();
              });
            },
            function() {
              var $span = $(this);
              $span.css('background-color', '');
              scope.$apply(function() {
                scope.wordUnderCursor = "";
              });
            }
          );
        }
      });
    }
  }
});

html:

   <body ng-controller="MainCtrl">
     Paragraph 1:
     <input type="text" ng-model="model.paragraph1"></input> <br />
     Paragraph 2:
     <input type="text" ng-model="model.paragraph2"></input>

    <p word-under-cursor="model.word" word-under-cursor-content="model.paragraph1"></p>
    <p word-under-cursor="model.word" word-under-cursor-content="model.paragraph2"></p>
    Word: {{model.word}}
  </body>

http://plnkr.co/edit/vRwCdXhtEFm7A4au1ago?p=preview

关于javascript - 如何使用 AngularJS 获取光标下的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26669472/

相关文章:

javascript - Twitter Bootstrap 附加奇怪的行为

javascript - 使用 PHP 和 REGEX 解析 JS 脚本以获取 JS 变量值

javascript - 保持图像的 3D 立方体在同一侧继续过渡

javascript - 从 JS 类加载外部 JS 文件

javascript - Coffeescript 在页面上打印 HTML,而不是渲染它

javascript - 如何使用下拉列表填充 Google 饼图?

javascript - 通过 AJAX 使用 JQuery 获取 HTML id

javascript - Dialog 中的事件和 UI 参数是什么

html - Flexbox 布局 - 四个 DIVS + Fullheight DIV

html - 响应式内容+侧边栏 : min-width for sidebar breaks in new line