1

I'm learning AngularJs and I'm playing with a third party Javascript component. At a certain point the control is initialized as follows:

$(document).ready(function () {
    $('#SomeId').initialize();
});

Is there a way to convert this to something more Angularish? I don't want to manipulate the DOM from the controller, but I'm not sure how to initialize this.

1
  • 2
    You can create a directive for that functionality and move the DOM manipulation and initialisation code there. Read more about directive Commented Aug 31, 2014 at 19:22

2 Answers 2

3

This code is not necessarily wrong as is. What you want to be careful about is javascript outside of the angular context (jQuery callbacks/plugins etc) manipulating $scope values because those functions will not trigger an angular digest loop, and will result in a disconnect between the DOM and the $scope.

Here is some more information about this cycle and what you need to know about it: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Here is a common use case with jQuery (and also why you should try to use angular services (ie: $http) instead:

// When you manipulate the $scope with a non-angular callback,
// you have to run $scope.$apply() to tell angular about the 
// change in order to repaint the DOM

$.get( "/getUser", function( data ) {
  $scope.user = data; // set $scope data in callback
  $scope.$apply(); // run digest so anything in the DOM binded to the {{user}} model gets updated
});
Sign up to request clarification or add additional context in comments.

Comments

2

Generally you don't need to manipulate the DOM like this with Angular...so you really don't need jQuery. Using an Angular "directive" is the declarative, encapsulated way to do it in Angular. There are a ton of 3rd party components out there for you to use that have been built properly with directives: I would recommend using these rather than trying to convert a jQuery plugin (which is really just adding the jQuery bloat for things that you already have access to with Angular). A good place to start looking for Angular directives that you can use is http://ngmodules.org/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.