3

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
});
0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks to your answer,but this method "get" the js file asynchronous and functions run with delay.this delay is so bad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.