Chris Townsend Chris Townsend - 4 months ago 9x
AngularJS Question

Determining where user is in application and loading different Angular scripts

I'm using Laravel and Angular to build a fairly large web application. I am using various angular modules which will have their own controllers, directives and views.

I want to be able to load in a different JS file depending on the current location. E.g. a route namespace like Admin or dashboard. I'm just trying to work out the best way to do it.

For example I could have something like this as my header in a blade template

<!doctype html>
<meta name="viewport" content="width=device-width" />

<link href="" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('audit-generator/css/angular-material.css') }}">
<link rel="stylesheet" href="{{ asset('audit-generator/css/style.css') }}">

<!-- Insert Angular module file based on location -->

@if(Route::getNamespace() == 'Admin')
<link href="my-angular-module.js" rel="stylesheet">

<body ng-app="ueppl" ng-cloak>

I have some idea how I could implement this but just interested if there would be a better way of dynamically loading in a script.


This isn't really an answer, but it's too long for a comment :)

The way I handle it is by using @yield('scripts') and @yield('styles') in my master layout blade. Then within a blade template that would only be shown inside a namespace like Admin or Client, etc., I use @section('scripts') to include the necessary files in the view.

Here is a quick example (reduced for brevity)

<!DOCTYPE html>
<html lang="en">
    <!-- Dynamically Loaded Styles -->
    <!-- Dynamically Loaded JavaScript -->

Then in my individual views, as needed, I can include a file using something like

<-- A view that only Admin namespace would see -->
    <script src="{{ elixir('assets/js/admin/adminOnly.js') }}"></script>

This might be too much control for what you need, ie: you're required to load it for each view if it's the same file. If that's the case, I believe your approach is easier to implement as it'll keep your app DRY.

Hope this information helps!