Chris Townsend Chris Townsend - 6 months ago 17
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>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>


<link href="https://fonts.googleapis.com/icon?family=Material+Icons" 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">
@endif
</head>

<body ng-app="ueppl" ng-cloak>
@include('audit-generator.templates.harbour-header')
@include('audit-generator.templates.header')
@if(!$errors->isEmpty())
@include('errors.errors')
@endif
@yield('content')
@include('audit-generator.templates.footer')
</body>
</html>


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.

Answer

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">
<head>
    <!-- Dynamically Loaded Styles -->
    @yield('styles')
</head>
<body>
    <!-- Dynamically Loaded JavaScript -->
    @yield('scripts')
</body>
</html>

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

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

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!