I have the following controller, that on start-up queries the server for a list of items, which gets the basic details for all items. Then, when a user clicks on an item from the list, it queries the server to return all of the item information, including some SVG data.
function ItemsCtrl($scope, $http) {
$scope.items = [];
$scope.selectedItemDesign = null;
$http.jsonp('/items/all?callback=JSON_CALLBACK').
success(function (data) {
$scope.items = data;
});
$scope.getItem = function (item) {
var index = $scope.items.indexOf(item);
if (!$scope.items[index].SVG) {
$http.jsonp('/items/byid/' + $scope.items[index]._id + '?callback=JSON_CALLBACK').
success(function (data) {
$scope.items[index].SVG = data.SVG;
$scope.selectedItemDesign = $scope.items[index].SVG;
});
} else {
$scope.selectedItemDesign = $scope.items[index].SVG;
}
};
}
The SVG data is then bound directly to the view via:
<div class="span9" ng-bind-html-unsafe="selectedItemDesign">
The problem I have is that I want to be able to attach events to tags in the SVG so as to allow users to interact with the SVG (simple onClick events), but I can't figure out how to do this...
I thought that after the line; $scope.selectedItem = $scope.items[index];
I would then be able to access the DOM and attach the events, but that isn't the case (the DOM hasn't been updated yet). I've looked at the information on directives too and while I've managed to get a directive set up to do the operations I need, it doesn't fire when the SVG is changed (and even then I'm not sure if it's pre/post DOM update).
You're right that you should be adding the onClicks to your SVGs after the DOM is rendered, and that that work should be done in a directive.
The hard part (and this is a recurring issue) is that there's no event that tells you when you should start adding those onClicks. Angular has no way of telling you, since it doesn't know when the DOM is ready. You'll have to add something to the directive that figures this out heuristically, by using jQuery to watch the DOM periodically with a setTimeout and figure out when it's ready for you.