Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regular javascript for code inside ng-view (angularjs)

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
});
like image 914
goldensausage Avatar asked Oct 18 '22 07:10

goldensausage


1 Answers

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.

like image 120
ManuKaracho Avatar answered Oct 21 '22 01:10

ManuKaracho