Dynamic Load Files on Demand for AngulerJS Learning

  • 2021-07-18 07:12:47
  • OfStack

Before that, we must first understand a few things:

$q

Introduction:

$q: It mainly solves the problem of asynchronous programming, which refers to describing the interaction between the action result of asynchronous execution represented by an object through a commitment behavior, which may or may not be completed at any time.

We understand the $q service through a short story.

I bought it outside at noon, called for fried rice, asked for it to be sent to the company and gave the boss a specific address. This process is $q. defer; The food cannot be delivered immediately, so this is a request for deferred response; The boss said it would be delivered as soon as possible. That is, the boss gave me a promise promise;; I can wait while working, which shows that this request is an asynchronous process. In this way, the deferred asynchronous request is established. Is an deferred. Meals are sent to me to receive, and this process is called deferred. resolve (data) response event; If the rice is sold out, the boss will tell me that I can't do it, that is, refuse my request, that is, deferred. reject (error); The boss can tell me that I can't do it at any time, as long as he hasn't delivered the meal. It's almost downstairs. Tell me to pick it up. This is to notify deferred. notify (data) so that the whole asynchronous callback process is complete. On the second day, many of us had to order food. So I can launch $q. all (req1, req2, req3.);

Use

We define it in the service that deferred is established between the beginning of the request, then return deferred. promise. deferred. resolve (data) when the data is retrieved. Similarly, we can receive notice or rejection in the middle.


var def = $q.defer();
def.resolve(data);
return def.promise;

Load on demand

First of all, we need to know the following points:

1. When to load:

Both ngRoute and uiRoute provide values in the resolve property that are preset before the route succeeds and then injected into the controller. Generally speaking, it is to wait for the data to be "in place" before routing (in fact, I don't think it can be called routing, because routing is a series of operations, including setting resolve attributes, etc.). You can refer to my last article.

2. How to register the loaded file:

angular has a boot function called bootstrap. According to the code design of angular, you need to define all controller before startup. It's like having a bag. You can put whatever you want in it before bootstrap. But once bootstrap is over, he will no longer accept any controller you put in.

There is only one way to solve this problem, that is, to actively register controller with provider of the main module. But because provider can't be used directly, we put it under the main module. The saved method can be used to register the page components loaded back asynchronously.

From the above, we know that we need to load files asynchronously

Realization


// controller
define(["app"], function(app) {
  app.config(["$stateProvider", "$urlRouterProvider", "$controllerProvider",
    function($stateProvider, $urlRouterProvider, $controllerProvider) {
      // angular There is a startup function called bootstrap ; 
      //  According to angular You need to define all the code design before starting controller ; 
      //  It's like there's a bag, and you're bootstrap Stuff whatever you want to put in before; 
      //  But 1 Dan bootstrap He won't accept anything you put in it controller It's over; 
      //  To solve this problem, only 1 A method is to use the main module provider Active registration controller ; 
      //  But because provider It can't be used directly, so we store it under the main module; 
      //  The saved method can be used to register the page components loaded back asynchronously. 
      app.registerController = $controllerProvider.register;
      app.loadFile = function(js) {
        return function($rootScope, $q) {
          // Pass $q Service registration 1 Delayed objects  deferred
          var def = $q.defer(),
            deps = [];
          angular.isArray(js) ? (deps = js) : deps.push(js);
          require(deps, function() {
            $rootScope.$apply(function() {
              //  Success 
              def.resolve();
              // def.reject()  Unsuccessful 
              // def.notify()  Update status 
            });
          });
          // Pass deferred Delay object, you can get 1 Promise promise , and promise Returns the completion result of the current task 
          return def.promise;
        };
      }
      $urlRouterProvider.otherwise('/index');
      $stateProvider.state("index", {
        url: "/index",
        template: " This is the home page "
      });
      $stateProvider.state("computers", {
        url: "/computers",
        template: " This is the computer classification page {{title}}",
        controller: "ctrl.file",
        resolve: {
          loadFile: app.loadFile("file")
        }
      });
      $stateProvider.state("printers", {
        url: "/printers",
        template: " This is the printer page "
      });
      $stateProvider.state("blabla", {
        url: "/blabla",
        template: " Others "
      });
    }
  ]);
});


// file.js
define(["app"], function(app) {
  app.registerController("ctrl.file", function($scope) {
    $scope.title = "-- Test  ";
  });
});

Source: requireLearn_jb51.rar


Related articles: