Reputation: 3472
I have some elements on the page already generated from my server, I am trying to get angularjs to register a click event on that element, how can I do that?
My span elements are:
<span id="SpanIdHere" class="data-field"></span>
I have a jquery event handler for each clicked field as I do not know which other way I can hook onto the click event, as the server has generated this html for me.
$("#report-html-content .data-field").click(function () {
var id = $(this).attr("id");
openFieldWithData(id);
});
This is the code that I have in my angular controller that will open an modal-overlay.
function openFieldWithData(selection) {
console.debug(selection);
$scope.SelectedField.Name = selection
$("#template-detail").addClass("open");
};
What I am trying to do is show a modal-overlay when each field is clicked in the UI.
This code fully works except when the jquery click event is called, only when I close the modal, the name of the field appears in the html.
<div id="template-detail" class="overlay-report">
<div class="inner">
<div class="panel panel-default">
<div class="panel-heading">
<h6>
Template field
<button ng-click="closePanel()" data-id="btnCloseOverlay" type="button" class="close pull-right">×</button>
</h6>
</div>
<div class="panel-body">
{{SelectedField.Name}}
</div>
</div>
</div>
</div>
Upvotes: 0
Views: 167
Reputation: 38490
The code inside the attached event handler lives "outside of Angular", so you need to manually tell Angular to trigger the digest loop. Otherwise the changes will not be reflected until something else triggers it.
You can use $apply
:
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.
If the openFieldWithData
is only called from outside of Angular you can:
function openFieldWithData(selection) {
$scope.$apply(function() {
$scope.SelectedField.Name = selection
$("#template-detail").addClass("open");
});
}
Otherwise you need to put it in the event handler:
$(".data-field").click(function() {
var element = $(this);
var scope = element.scope();
scope.$apply(function() {
openFieldWithData(element.attr("id"));
});
});
Upvotes: 1