2

I have application in angularJs and it will have different modules with different JS files.for js file optimization I am going to implement requireJS.

There is (broken) plunker

My angularJs code is like this in app.js:

var app = angular.module("webapp", ['ngRoute']);

app.run(['$rootScope', '$state','$urlRouterProvider',
function ($rootScope,   $state,$urlRouterProvider) {
$urlRouterProvider.otherwise('/index.html');
$stateProvider
    .state('root.home',{
        url: '/index.html',
        views: {
            'header': {
                templateUrl: 'modules/header/html/header.html',
                controller: 'headerController'
            },          
            'content-area': {
                templateUrl: 'modules/home/html/home.html',
                controller: 'homeController'
            },
            'footer': {
                templateUrl: 'modules/common/html/footer.html',
                controller: 'footerController'
            }
        },
        data: {
            displayName: 'Home',
         }
    })
.state('root.about',{
        url: '/index.html',
        views: {
            'header': {
                templateUrl: 'modules/header/html/header.html',
                controller: 'headerController'
            },          
            'content-area': {
                templateUrl: 'modules/home/html/about.html',
                controller: 'aboutController'
            },
            'footer': {
                templateUrl: 'modules/common/html/footer.html',
                controller: 'footerController'
            }
        },
        data: {
            displayName: 'About',
         }
    })

  }]);

I added the following code in my main.js file

require.config({
    baseUrl: "",

    // alias libraries paths.  Must set 'angular'
    paths: {
        'angular': 'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min',
        'angular-route': 'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.min',
        'angularAMD': 'http://cdn.jsdelivr.net/angular.amd/0.2.0/angularAMD.min'
    },

    // Add angular modules that does not support AMD out of the box, put it in a shim
    shim: {
        'angularAMD': ['angular'],
        'angular-route': ['angular']
    },

    // kick start application
    deps: ['app']
});

and also added requirejs in html

 <head>
        <link rel="stylesheet" href="style.css">
        <script data-main="main.js" src="http://marcoslin.github.io/angularAMD/js/lib/requirejs/require.js">   </script>
<script src="js/app.js"></script>

 </head>

how can I define requirejs module or implement with my angularjs UI-Rooter?

EXTEND:

In your Example You added the above code in app.js

define([], function() {

  var app = angular.module('webapp'); 
  return app;

})

I added above code to script.js.Also In my app.js file contain all the UI router things and I changed the main.js with following code

require.config({

    //baseUrl: "js/scripts",
    baseUrl: "",

    // alias libraries paths
    paths: { 

        // here we define path to NAMES
        // to make controllers and their lazy-file-names independent

        "testController" : "modules/test/js/controller/testController",

    },

    deps: ['js/script'] // changed section
});

but in my browser console I am gettnig this error "NetworkError: 404 Not Found .../default/app.js" .how can I solve this issue.I directly added this js file through the html.but I am getting this error.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sarath
  • 1,459
  • 3
  • 22
  • 38
  • I tried to provide detailed how to [here](http://stackoverflow.com/a/27754025/1679310) and [there](http://stackoverflow.com/a/27466890/1679310). It includes working examples... and, if you need resolve as well [there is another](http://stackoverflow.com/a/30628429/1679310) – Radim Köhler Jun 04 '15 at 11:46
  • For calling the module based js we need to put the controller path in require config is it right? – Sarath Jun 04 '15 at 13:07
  • I'd say yes. Just play with my examples.. that really should give you the answer.. I guess ;) – Radim Köhler Jun 04 '15 at 13:08
  • I am new to requireJs So i didn't get the exact idea. i am getting following error in my browser console . "Uncaught Exception: Error: Script error for: app http://requirejs.org/docs/errors.html#scripterror at (compiled_code):1" error in my browser console – Sarath Jun 04 '15 at 13:17
  • I would suggest. Take my plunker. Adjust it with your own stuff.. Once you have that running you can compare with the original and do changes. OR create broken plunker, and I can take a look and if I will know... Does it make sense? – Radim Köhler Jun 04 '15 at 13:19
  • Hi I just create one plunker with my code it's not working . Can you please have a look :http://plnkr.co/edit/iV7fuG5mkoTQ2JoKk9e0?p=preview – Sarath Jun 04 '15 at 14:07
  • Will take a look give me few minutes – Radim Köhler Jun 04 '15 at 14:14
  • ok thanks for your support – Sarath Jun 04 '15 at 14:20
  • Best way to go is to follow this seed: https://github.com/tnajdek/angular-requirejs-seed I have used it in 2 projects and have very good experiences. – Christian Jun 04 '15 at 11:59

1 Answers1

1

As discussed in comments and related to this plunker: http://plnkr.co/edit/iV7fuG5mkoTQ2JoKk9e0?p=preview

I followed the Q & A:

angular-ui-router with requirejs, lazy loading of controller

And updated that plunker and make it working.

There are many changes. E.g. we should keep a reference to controller providers:

var app_cached_providers = {};

app.config(['$controllerProvider',
  function(controllerProvider) {
    app_cached_providers.$controllerProvider = controllerProvider;
  }
]);

And inside of our mapped controllers (e.g. controller_home.js) register that:

define(['app'], function (app) {

    // the Content Controller
    // is added into the 'app' module
    // lazily, and only once
    app_cached_providers
      .$controllerProvider 
      .register('HomeCtrl', function ($scope) {
        $scope.message = "Message from HomeCtrl"; 
    });
}); 

Also, this would be a helper method to make other stuff a bit simplier

var loadController = function(controllerName) {
  return ["$q", function($q) {
      var deferred = $q.defer();
      require([controllerName], function() {deferred.resolve(); });
      return deferred.promise;
  }];
}

And here we will use it to extend state definitions. Firstly the root state:

    $urlRouterProvider.otherwise('/root');
    $stateProvider
        .state('root',{
        url: '/root',
        templateUrl: 'view_root.html'
      });

Now states loading controller async way:

      var root_home = {
        //url: '/index.html',
        url: '/home',
        views: {
          '' : {templateUrl: 'view_home.html', controller: 'HomeCtrl' },
        },
        data: {
            displayName: 'Home',
        },
        resolve : { }
      };
      root_home.resolve.loadTopMenuCtrl = loadController("HomeCtrl");

    var root_about = {
        //url: '/about.html',
        url: '/about', 
        views: {
          '' : {templateUrl: 'view_view1.html', controller: 'View1Ctrl' },
        },
        data: {
            displayName: 'About',
        },
        resolve : { }
    };
    root_about.resolve.loadContentCtrl = loadController("View1Ctrl");

    $stateProvider
      .state('root.home', root_home)
      .state('root.about', root_about)

Check it all in action here

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Is it possible to do the requirejs implementation with minimum change of my code. Because I already developed bulk of modules.May be for testing i need to changes all state then only i will get the exact result – Sarath Jun 05 '15 at 04:51
  • Well, honestly, I expected kind of: *"Thanks you've made my code working."* ;) Really not sure what should I do more for YOU. I provided you with detailed description and showed how to fix all the issues in your plunker *(and there were many of them, which are simply breaking the code.. it will never run - compare yours and mine)*. Anyhow, if you think I am not answering your question, and you need different answer - let me know, I will delete my post. Wish you get your answer, I really do – Radim Köhler Jun 05 '15 at 05:50
  • I added **My error section** in your answer section. Can you please have a look – Sarath Jun 05 '15 at 09:15
  • Firstly, this edit belongs to your question, not to answer (I moved that)... and maybe even... you should think about different question.. If my is still not helping. Anyhow.. I will take a look, now I need a bit more time... – Radim Köhler Jun 05 '15 at 09:16
  • And also i am getting one more error like this "Error: [$injector:unpr] http://errors.angularjs.org/1.3.12/$injector/unpr?p0=authServiceProvider%20%3C-%20authService" its from other js file.I think it's dependency issue.How can i solve this issue? – Sarath Jun 05 '15 at 09:53
  • Sorry, I cannot help. I observed your latest notes.. but they do not make sense to me. I showed you how to make it working (all changes n app.js, script.js, main.js) and you change them again... and surprised that it is not working... Why won't you change your code as mine is? In the linke I've sent you I explain each and every part of the code.. why they are needed. That's everything I can do here. sorry. Good luck – Radim Köhler Jun 05 '15 at 10:10
  • I am using some other controller on my end but i didn't applied any requirejs code in that js file It will make any issue? – Sarath Jun 05 '15 at 10:28