当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Highlight Text after ng-view location Change in Angularjs

问题描述:

I am trying to highlight some text using this jquery highlight plugin after a user changes the ng-view location; The text to be highlighted is on the returned page.

On success of the view change, I run the highlight() method:

$scope.$on('$locationChangeSuccess', function(event) {

console.log('success');

$("p").highlight(["text"]);

});

My success log is printed, however the text never highlights.

My files are loaded correctly because I can run the action on my browser console and my defined text gets highlighted, so I'm not sure what's wrong here. Any ideas?

Thanks much!

网友答案:

When writing Angular code, It's generally discouraged to manipulate the DOM directly, as one would typically do with jQuery. Instead, you should use Angular's logical attributes to create the appearance of a changing DOM. While I can't understand why your particular example doesn't work, an alternative and more "Angular" solution could be something like this:

<p ng-style="{'background-color': highlight}"></p>

And then in your JS file, you'd set the value of highlight

if bla
  $scope.highlight = '#FFFF88';
else
  $scope.highlight = '#FFFFFF';
网友答案:

I was able to achieve this only by using Angular's $timeout and creating a timeout method

$scope.$on('$locationChangeSuccess', function(event) {
    console.log('success');
    $timeout(callTimeout, 1);
});
...
function callTimeout(){
    $("p").highlight(["text", "text2", "text3"]);
}

I'm not sure why yet, but it would not work without this. I'll update this answer if I find the solid reason

Thanks

分享给朋友:
您可能感兴趣的文章:
随机阅读: