5

First time using angularJS here. Basically, i used the routing service, so i have a with routing calling in a template with html code in it. I also have all these regular javascript functions that are required for the code in the template to display properly (slideshows and among many other things).

When i run i get all these null errors (it seems that my JS functions cant find various elements because either it cant access code in the ng-view/template or it got run before ng-view/template got loaded).

When i paste all of my javascript functions in the controller that i assigned for that template, it worked. But i have a feeling im not supposed to do that. What is the correct way to make this work? Thanks.

var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider){
    $routeProvider
    .when("/",{
        templateUrl:"about.html",
        controller:"aboutCtrl"
    })
    .when("/aboutus", {
        templateUrl:"entertainment.html"
    })
});

app.controller('aboutCtrl', function($scope){
    //placed regular javascript/jquery code here to make it work
});
goldensausage
  • 229
  • 1
  • 2
  • 11

1 Answers1

3

Your jQuery functions probably don't work, because the elements on which they shall be executed can't be found when you are on a different route.

Ways to fix that:

  • Cleanest way: Wrap your slideshow into an angular directive, in which you define its html template and its necessary code. The code will only be executed if the template is called. Since you are just starting out with Angular, you would probably need some more help on this.
  • Put the code into the template: You can also try to put your needed JS into the template via a < script >< /script > block. That way the code will only be evaluated when your template is loaded.
  • As you said, you can also put your code into your controller. But it will bloat your controller and make your code messy quickly

Options 2 & 3 will work, but will also quickly turn your app into a huge mess. I would definately recommend to dig more into angular directives, to keep your code clean.

Maybe this tutorial could be a good starting point for you.

ManuKaracho
  • 1,180
  • 1
  • 14
  • 32
  • thanks a bunch. I will research more and attempt the first solution as it seems to be the most elegant one. – goldensausage Jun 23 '16 at 19:13
  • I managed to put all my javascript code into separate directives (using templateUrl to link an html file containing only the JS code). But another problem arose. offsetHeight is reporting incorrect heights of certain divs with text in them (it reports correct after i refresh it again). I resolved this issue before by doing $(window).bind("load", function() which allows everything to load and render first before running. But now this function wont even run at all when used inside a template. – goldensausage Jun 27 '16 at 08:47