Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How to load JS files in route `when` controller?

I have a web application using AngularJS, but each view has different JS files. How can I load JS files in route when controller?

var app = angular.module("myApp", ['ngRoute']);
app.config(['$routeProvider',
    function ($routeProvider) {
        $routeProvider.
                when('/member/master', {
                    templateUrl: 'templates/two-grid.html',
                    controller: 'memberMaster'
                }).
                when('/core/master', {
                    templateUrl: 'templates/two-grid.html',
                    controller: 'coreMaster'
                }).
                when('/user/master', {
                    templateUrl: 'templates/two-grid.html',
                    controller: 'userMaster'
                }).
                otherwise({
                    redirectTo: '/dashbourd'
                });
    }]);

app.controller('coreMaster', function ($scope) {
    //I want to load js/coremaster.js here
});
app.controller('memberMaster', function ($scope) {
    //I want to load js/membermaster.js here
});
app.controller('userMaster', function ($scope) {
    //I want to load js/usermaster.js here
});
like image 906
vahid mehrjooei Avatar asked Nov 26 '25 22:11

vahid mehrjooei


1 Answers

I think that $stateProvider and ocLazyLoad can help you.

See a example:

$stateProvider
.state('login',{
    templateUrl:'views/pages/login.html',
    controller: 'LoginCtrl',
    controllerAs: 'vm',
    url:'/login',
    resolve: {
        loadMyDirectives:function($ocLazyLoad){
            return $ocLazyLoad.load(
                {
                    name:'aExample',
                    files:[
                        'scripts/controllers/login.js',
                    ]
                });
        }
    }
})

And you can see other examples here: https://github.com/ocombe/ocLazyLoad/blob/master/examples/complexExample/js/app.js

like image 106
Nguyen Sy Thanh Son Avatar answered Nov 29 '25 13:11

Nguyen Sy Thanh Son



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!