Skip to content Skip to sidebar Skip to footer

Angularjs Not Working With Jquery Displayed Html

I have a Html page with a text box and am using a bit of AngularJS to display the count of characters remaining -

Solution 1:

This is tricky because you're attempting to modify data outside of Angular's "world". It seems easy enough to do, but because you're creating elements that are bound to Angular, it's taking some liberties with the content that can go in there, or rather how it's "rendered" by Angular.

tl;dr; - you need to use the $sce provider with Angular inside a controller in order to "trust" new content as HTML; use $sce.trustAsHtml(content). Best approach would be to actually create a controller here and attach it to your form with ng-controller.

The trick will be to use ng-change on the textarea to hook to the text changing instead of using jQuery. From a recently converted hardcore jQuery guy to one who now prefers to live inside Angular's "world", I can tell you that using events, controllers, and http.get has a lot of similarities and is easy to work with.

Here's some pseudo-code to quickly get you going:

HTML Pseudo Markup:

<formng-controller="myController as ctrl">
  ...
  <textarea...ng-model="textinput"ng-change="ctrl.updateLength()"></textarea><spanng-bind-html="ctrl.textRemainingDisplay"></form>

Notice ng-model in there - we'll use that in the change event handler. The other critical piece is the display, which we us ng-bind-html; the $sce provider below will give us a render in the format needed to bind without any further ado.

Javascript Pseudo markup:

angular.module("myModule",[]).controller("myController", function($scope, $http, $sce)
{
  this.updateLength = function()
  {
      this.textRemainingDisplay = $sce.trustAsHtml(500-this.textinput.length);
  }
});

You could [probably should] use a directive to do the same thing, I just think as someone who's also learning Angular that controllers are a little easier to digest. Difference would be some syntax on the controller (using directive instead and returning an object) and then the markup on the span would go something like <span mydirective></span> and the created directive would have the same scope as what we did above.

Again this is just pseudo-code, I haven't tested anything but it should work to get you a simple counter in pure Angular that doesn't require jQuery and Angular together.

HTH!

Post a Comment for "Angularjs Not Working With Jquery Displayed Html"