How to load scripts within a partial in Angular.js SPA

Asked

Viewed 1,320 times

0

Hello, I’m starting in Angular Js, and I’m doing a project in Single Page Application, in my index, I load some scripts and my ng-view, but in one of my partials, I need to load a script in it, it doesn’t make sense to directly load into the index, because I need DOM elements that are in my view, and it would be an unnecessary upload as not all users will get to this view. But I realized that the scripts within partials are not executed. Someone could give me a help, follow my index, main and partial codes. Thank you.

Index.html

<html lang="pt-br" ng-app="sistema">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <title>Index.html</title>
        <script src="/js/lib/angular.min.js"></script>
        <script src="/js/lib/angular-route.min.js"></script>
        <script src="/js/lib/angular-resource.min.js"></script>
        <script src="js/main.js"></script>
        <link href="/css/style.min.css" rel="stylesheet" />
        <script src="/js/lib/jquery.min.js"></script>
    </head>
    <body>            
        <ng-view></ng-view>
    </body>
</html>

Partial html.

<script src="caminho-do-meu-script.js"></script>
<script>
$(document).ready(function(){
    alert("aqui meu script inline");
});
</script>
<h1>Minha partial com scripts</h1>

Main.js

angular.module('sistema', ['ngRoute', 'ngResource'])
    .config(function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);

        $routeProvider.when('/teste', {
            templateUrl: 'partials/partial.html'
        });

        $routeProvider.otherwise({redirectTo: '/teste'});

    });

2 answers

1

Have you researched Controllers? Take a look, I think that’s what’s missing from your Single Page Application.

For example:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<button onclick="customAlert('aqui meu script inline')">Alert</button>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    customAlert = function(message) {
        alert(message);
    }
});
</script>

</body>
</html>
  • Man, I was really looking for something like the Lazyload that responded down here. But in case I needed it here, putting the script in the controller solves my problem, thank you very much!

  • Glad you could solve your problem. Hugs.

1


They are not executed because they need to be linked to a module which, if there is no insertion service, should be initiated at the beginning of the application.

The method I know, and also the most commonly used (which was used as a basis in the development of Angular2 as well) is the ocLazyLoad.

It provides not only a crude lazyload, or lazyload of Js files, but of a wide variety of extensions as well as several loads within a same call, among other options. Is quite complete.

On the documentation page you can see the use of it in more detail: https://oclazyload.readme.io/docs

Basic example:

myApp.controller("MyCtrl", function($ocLazyLoad) {
    $ocLazyLoad.load('testModule.js');
});

What struck me most about him was the fact that it could be used in conjunction with ui.router within a resolve, which I think would be interesting for you as well. From what you said, it seems to be a restricted area, where not all users will access.

By joining these two techniques, you can use the resolve to prevent view (and consequently the files) are loaded while there is no user authentication.

Here is an example of a restricted area that I use by combining the ui.router and ocLazyLoad:

.state('app-adm', {
    url: '/Admin',
    views: {
        'main': {
            templateUrl: 'app/adm/main.html'
        }
    },
    data: {
        requerLogin: true, //Login obrigatório
        usuarioTipo: 1, //Tipo do usuário
        usuarioCargo: ['admin','master'] //cargo do usuário
    },
    resolve: {
        lazyLoad: function($ocLazyLoad) {
            return $ocLazyLoad.load({
                name: ['app.admin'],
                files: ['dist/js/admin.min.js']
            });
        }
    }
})

In this case, before the resolve is started, it does login validation, type of user and if the post has access to that view. If all this is ok, it will load the module, otherwise it will block access.

Remembering that the validation and verification I commented is done in another script, using the stateChangeStart, which is an event of ui.router.

  • Dude, I was taking a look at this Lazyload, that’s what I was asking if it existed. Thank you so much for the answer :)

  • @Aldofernandesjunior is excellent! Leaves the application much more dynamic, agile, I have not seen any against yet.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.