我需要在我的应用程序中使用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',''); }
);
答案 0 :(得分:1)
使用指令:
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>