Angularjs and requirejs integration

Summary
angularjs and requirejs integration, AMD/CMD
directory

[TOC]
1. Overview
1.1 Why integrate?

    Since the various dependencies of angularjs must be loaded in sequence according to the js script, this makes developers very troubled by
    the conflict of multiple import and execution of scripts, as well as the impact on performance efficiency.
    1.2 Script loading framework (AMD/CMD)
    requirejs supports AMD and CMD

    seajs supports AMD, and I don’t know much about Jingdong’s use at present. I use requirejs for testing
    . 1.3 New features of     angularjs

    angularjs-1.5 has added many new features.

Component is easy to switch to angular2, but now I receive a message that angular has a compiler saying that angular1 can be directly compiled to angular2

    component routing component-router
    1.4 angularjs plugins

        By the way, introduce some commonly used plugins

    ngFileupload angular-based files Upload demo example
    ui-router routing
    angular ui other ui plugins can use these
    Other extension modules of angular material responsive framework
    include export csv, drag and drop, scroll bar
    integration code
    directory path

-lib/jquery/jquery-1.8.0.min.js
-lib/angular/angular.min.js
-lib/angular/angular -route.min.js
-lib/requireJS/require.js

-scripts/inject.js
-scripts/test.js
-scripts/app.js
-main.js

-index.html
-pages/app.html
-pages/home .html
-pages/index.html

(requirejs entry) main.js

/**
* require the main entry, related configuration dependencies are configured from here
*/
require.config({
    baseUrl: "/",
    //Every time js is newly loaded, To avoid caching
    urlArgs: "bust=" + (new Date()).getTime(),
    paths: {
        'jquery': 'lib/jquery/jquery-1.8.0.min',
        'angular': 'lib/angular/angular.min',
        'angular-route': 'lib/angular/angular-route.min',
        'app': 'scripts/app',
        //入口注入脚本
        'inject' : 'scripts/inject'
    },
    shim: {
        'angular': ['jquery'],
        'angular-route': ['angular']
    }
});
require(["inject"], function() {});

页面(index.html)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script data-main="main" src="lib/requireJS/require.js"></script>
    <title>angularJs & requireJs</title>
</head>
<body>
<!--Program entry-- >
<app/>
</body>
</html>

Inject script (inject.js)

!(function () {
    'use strict';
    //Of course, the data of this scripts can be dynamically obtained from the server to load
    var scripts = ['scripts/test'];

    //depending on script loading
    require(scripts, function () {
        //rendering
        angular.bootstrap(document, ['app']);
    });
}());

main module script ( scripts/app. js)

    Here is the basic definition of the main module. Finally, the object of the module must be returned for dependencies and then the next step.

define("app",["angular",'angular-route'], function(a, r) {
    var app = angular.module('app', ['ngRoute'])
        .controller("IndexCtrl",["$scope", function($scope) {
        $scope.name = "王五";
    }])
        .component('app', {
        templateUrl: "pages/app.html"
    })
        .config(["$routeProvider",
            function($routeProvider) {
                $routeProvider.
                when("/home", {
                    templateUrl: "pages/home.html",
                    resolve : {
                        $routeChangeSuccess : function($rootScope) {
                            $rootScope.appName = '这里是appName';
                        }
                    }
                }).
                when("/index", {
                    templateUrl: "pages/index.html",
                    controller: "IndexCtrl"
                })]);
    return app;
});

app component template (pages/app.html)

<h2> Head</h2>
content:
<java></java>
<div ng-view></div>
<h2>bottom</h2>

component script (scripts/test.js)

//This must depend on the app script
define (["app"], function (app) {
    //Define the java component
    app.component('java', {
        template: "I am a java programmer",
    });
});

view routing home.html

here is home . html

result
access route

http://localhost:8080/app.html#/home
结果

html展示: html dom结果: dom



--文件上传demo
<body ng-app="fileUpload" ng-controller="MyCtrl">
  <form name="myForm">
    <fieldset>
      <legend>Upload on form submit</legend>
      Username:
      <input type="text" name="userName" ng-model="username" size="31" required>
      <i ng-show="myForm.userName.$error.required">*required</i>
      <br>Photo:
      <input type="file" ngf-select ng-model="picFile" name="file"   
             accept="image/*" ngf-max-size="2MB"required
             ngf-model-invalid="errorFile">
      <i ng-show="myForm.file.$error.required">*required</i><br>
      <i ng-show="myForm.file.$error.maxSize">File too large
          {{errorFile.size / 1000000|number:1}}MB: max 2M</i>
      <img ng-show="myForm.file.$valid" ngf-thumbnail="picFile" class="thumb"> <button ng-click="picFile = null" ng-show="picFile">Remove</button>
      <br>
      <button ng-disabled="!myForm.$valid"
              ng-click="uploadPic(picFile)">Submit</button>
      <span class="progress" ng-show="picFile.progress >= 0">
        <div style="width:{{picFile.progress}}%"
            ng-bind="picFile.progress + '%'"></div>
      </span>
      <span ng-show="picFile.result">Upload Successful</span>
      <span class="err" ng-show="errorMsg">{{errorMsg}}</span>
    </fieldset>
    <br>
  </form>
</body>



//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);

app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
    $scope.uploadPic = function(file) {
    file.upload = Upload.upload({
      url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
      data: {username: $scope.username, file: file},
    });

    file.upload.then(function (response) {
      $timeout(function () {
        file.result = response.data;
      });
    }, function (response) {
      if (response.status > 0)
        $scope.errorMsg = response.status + ': ' + response.data;
    }, function (evt) {
      // Math.min is to fix IE which reports 200% sometimes
      file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
    });
    }
}]);



--

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326701316&siteId=291194637