Created
May 11, 2016 16:04
-
-
Save lucnap/96844fedfcd6e89b90513c10f4dbf3dc to your computer and use it in GitHub Desktop.
Angular and Jquery interoperability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
////////////////// from angular to jquery | |
// in angular controller | |
$scope.execFn1 = function() { | |
document.dispatchEvent(new CustomEvent( 'testEvent1', | |
{ | |
detail: {mydata1: 'hello from angular'} | |
} | |
) | |
); | |
}; | |
// in jquery | |
$(document).on("testEvent1", function(e) { | |
console.log(e.detail); | |
}); | |
/////////////////////////////////////////////////////////////////// | |
////////// from jquery to angular | |
// in angular controller | |
$(document).on("eventFromJquery", function(e) { | |
console.log("hello, here we are inside angular context"); | |
$scope.someVar = "changed"; | |
$scope.$apply(); // <-- very important | |
}); | |
// in jquery context | |
$("#button2").on("click", function() { | |
// change some form field and notify angular with trigger("input") | |
$("#firstName").val("Luciano").trigger("input"); | |
// change some global variable. Here angula is not notified until we force a digest cicle | |
myVar1++; | |
// event triggered and caputered in angular with the previous function in the controller | |
// in the controller is triggered a digest cicle | |
$.event.trigger({ | |
type: "eventFromJquery", | |
message: "hey!", | |
time: new Date() | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment