Reputation: 211
I have a simple Angular webapp and I have problems when I re-visit a route. On first visit, the route's controller makes everything works as it should. On second visit, things break. The controller sets the dimension of a canvas element in the view. A stripped down example of the controller:
// app.js
var app = angular.module('noahdecocoApp', ['ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch']);
app.config(function ($routeProvider) {
$routeProvider
.when('/particle-page', {
templateUrl: 'views/particle.html',
controller: 'ptclCtrl'
})
});
// ptclCtrl.js
app.controller('ptclCtrl', function($scope){
var canvas = document.getElementById("ptclCanvas");
var ctx = canvas.getContext("2d");
ctx.canvas.width = 500;
ctx.canvas.height = 500;
});
//particle.html
<canvas id='ptclCanvas'></canvas
The first time around, this works fine. The second time around, the canvas resets to it's original default values. I'm not sure why this happens? Am I doing this wrong, is there an Angular way to do this? The second thing I'm trying to do is add and animate particles which I can't achieve because I suspect of the same problem, my Array variables only initialise on first load. Any help is appreciated, I've been trying to find the solution for weeks!
Upvotes: 0
Views: 382
Reputation: 12018
That is not Angular at all. In angular you never ever ever (repeat that with me) do DOM manipulation in a controller. If you find doing that yourself, don't.
DOM manipulation is done in a directive, so you could do something like:
app.directive('resizeCanvas', function() {
return {
link: function(scope, element, attrs) {
var ctx = element[0].getContext("2d");
ctx.canvas.width = 500;
ctx.canvas.height = 500;
}
};
});
and then:
<canvas resize-canvas></canvas>
That will resize it for you, no controller involved.
Upvotes: 1
Reputation: 236
Put your logic that needs to be executed exactly once in the run block or the config. That way it gets initialized only once
Order of execution:
app.config()
app.run()
app.controller()
var app = angular.module('myApp',[]);
app.run(function() {
});
Upvotes: 0