Kevin Vincent Kevin Vincent - 3 months ago 13
AngularJS Question

How to instantiate a canvas in a dialog?

I would like to instantiate a canvas available in a dialog but it always returns a null object. In my JavaScript file I have :

$scope.showAdvanced = function(ev) {
var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && $scope.customFullscreen;
var myDialog = $mdDialog.show({
controller: DialogController,
templateUrl: '../templates/dialogCanvas.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
fullscreen: useFullScreen,
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
$scope.$watch(function() {
return $mdMedia('xs') || $mdMedia('sm');
}, function(wantsFullScreen) {
$scope.customFullscreen = (wantsFullScreen === true);
});
};


In my HTML file (dialogCanvas.html), I have this tag :

<div id="back">
<canvas id="canvasZone"></canvas>
</div>


And finally in the controller function I try to instantiate the canvas by doing this :

function DialogController($scope, $mdDialog) {
var canvas = document.getElementById('canvasZone');
}


But the object is null.

Answer

Try get the canvas object using $timeout or $evalAsync.In this way the function inside will get executed after DOM manipulating.

$scope.$evalAsync(function(){
    var canvas = document.getElementById('canvasZone');
});

or

$timeout(function(){
    var canvas = document.getElementById('canvasZone');
},0);