angular入门框架

目录

首先把项目地址贴出:笔者也只是刚入门而已,每一步都走的很困难,基本每一个知识点都是靠百度,刚开始感觉很吃力,慢慢发现吃力才有收获。
https://git.oschina.net/xxd0x00/angularjstest.git
angular首先是一个框架,所以他是有类似于后台的MVC分层的,同时他还有run方法,依赖模块,监听,路由,双向数据绑定,“页内锚点”,一般大型项目使用angular是十分明智的,或者你们项目组有 前端工程师,不然你只是一个“写接口的”angularjs看看了解就好,

首页分析

首先angular能很好的支持页面间的路由跳转+强大的数据绑定 这两个核心,贴出文件结构图
angular入门框架_第1张图片

全局的html文件


<html lang="en" data-ng-app="app">// 这是重点
div>
<head>
    <meta charset="utf-8" />
    <title>demotitle>   
    <meta name="description" content="app, web app, responsive, responsive layout, admin, admin panel, admin dashboard, flat, flat ui, ui kit, AngularJS, ui route, charts, widgets, components" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="stylesheet" href="css/bootstrap.css" type="text/css" />
    <link rel="stylesheet" href="css/animate.css" type="text/css" />
    <link rel="stylesheet" href="css/font-awesome.min.css" type="text/css" />
    <link rel="stylesheet" href="css/simple-line-icons.css" type="text/css" />
    <link rel="stylesheet" href="css/font.css" type="text/css" />
    <link rel="stylesheet" href="css/app.css" type="text/css" />
    <link rel="stylesheet" href="css/custom.css" type="text/css" />
    <link rel="stylesheet" href="css/web.contextmenu.css" type="text/css" />
    <link rel="stylesheet" href="css/bootstrap-datetimepicker.css" type="text/css" />
    <link rel="stylesheet" href="css/bootstrap-fileupload/bootstrap-fileupload.css" type="text/css" />


head>
<body ng-controller="AppCtrl">// 全局的一个controller
<div class="app" id="app"     
     ng-class="{'app-header-fixed':app.settings.headerFixed,
       'app-aside-fixed':app.settings.asideFixed,
       'app-aside-folded':app.settings.asideFolded,
       'app-aside-dock':app.settings.asideDock,
       'container':app.settings.container}" ui-view>// 最重要的ui-view  你暂时不需要知道这是干嘛的,你只需要知道你所有的页面都将被嵌套在这个 ui-view里面,

div>



<script src="vendor/jquery/jquery.min.js">script>


<script src="vendor/angular/angular.js">script>

<script src="vendor/angular/angular-animate/angular-animate.js">script>
<script src="vendor/angular/angular-cookies/angular-cookies.js">script>
<script src="vendor/angular/angular-resource/angular-resource.js">script>
<script src="vendor/angular/angular-sanitize/angular-sanitize.js">script>
<script src="vendor/angular/angular-touch/angular-touch.js">script>

<script src="vendor/angular/angular-ui-router/angular-ui-router.js">script>
<script src="vendor/angular/ngstorage/ngStorage.js">script>


<script src="vendor/angular/angular-bootstrap/ui-bootstrap-tpls.js">script>

<script src="vendor/angular/oclazyload/ocLazyLoad.js">script>

<script src="vendor/angular/angular-translate/angular-translate.js">script>
<script src="vendor/angular/angular-translate/loader-static-files.js">script>
<script src="vendor/angular/angular-translate/storage-cookie.js">script>
<script src="vendor/angular/angular-translate/storage-local.js">script> 


<script src="js/app.js">script>
<script src="js/config.js">script>
<script src="js/config.lazyload.js">script>
<script src="js/config.router.js">script>
<script src="js/main.js">script>
<script src="js/services/ui-load.js">script>
<script src="js/services/service.js">script> 
body>
html>

第一个app.js文件

整个前端需要依赖的模块,你就照着这个copy就行

'use strict';
// 依赖注入   依赖的模块
angular.module('app', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngTouch',
    'ngStorage',
    'ui.router',
    'ui.bootstrap',
    'ui.load',
    'ui.jq',
    'ui.validate',
    'oc.lazyLoad',
    'pascalprecht.translate',
    'ng.ueditor',
    'angularFileUpload',
    'ui.bootstrap.contextMenu'
]);

config.js

主要用于全局的函数,脸面的run方法相当于会一直的运行,检测你有没有登陆,并且可以定义一些全局的函数,比如跳转之类的。

// config

var app =
  angular.module('app')
    .config(
      function ($controllerProvider, $compileProvider,
                $filterProvider, $provide, $httpProvider) {

        // lazy controller, directive and service
        app.controller = $controllerProvider.register;
        app.directive = $compileProvider.directive;
        app.filter = $filterProvider.register;
        app.factory = $provide.factory;
        app.service = $provide.service;
        app.constant = $provide.constant;
        app.value = $provide.value;
        $httpProvider.defaults.headers.common = {
          Accept: "application/json, text/plain, */*"
        };

      }
    );
//相当于main
app.run(function($rootScope, storage, $http, $state){

  $rootScope.global = storage.get("QSLH_OW_MANAGER_GLOBAL") || {
      token:'',
      login: false,
      user_info: {}// 暂时写死xxd
  };

  $rootScope.go = function(args){
    $state.go(args);// 全局的跳转
  };

  if(!$rootScope.global.login){
      // 判断是否登录  如果没有登录,那就跳转到登录页面 ,

      $state.go("access.signin");
  }else{
      // 有登录,那就是 要给 http 赋值一个 token
    $http.defaults.headers.common['X-Security-Token'] = $rootScope.global.token;
  } 

});

congfig.router.js配置全局的跳转

'use strict';

/**
 * 配置路由
 */
angular.module('app').run(
    ['$rootScope','$state', '$stateParams',
        function($rootScope, $state, $stateParams){
            $rootScope.$state = $state;
            $rootScope.$stateParams = $stateParams;
            $rootScope.gateway = "/api";// 这个就是你的项目服务端的工程名字
}]).config([
    '$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider){
          $urlRouterProvider.otherwise('/app/manage/index');// 这个是uri上的匹配不上时,就会自动跳到这个页面
            $stateProvider
                .state('app', {
                    abstract: true,// 多层嵌套的最外层
                    url: '/app',
                    templateUrl: 'partials/app.html' // 这个页面里面可以包含很多的其他页面
                }).state('app.manage', {
                url: '/manage',
                template: '
'
// 这个template代表 将 app.manage.*所有的页面都将加载在 index.html中的
中,
}) .state('app.manage.index', { url: '/index', // 主页 templateUrl: 'partials/manage/index.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return //允许进行弹窗提醒 $ocLazyLoad.load('toaster').then( function () { return //会加载对应的js文件 $ocLazyLoad.load('js/controllers/manage/manage.js'); } ); }] } }).state('access', { url: '/access', template: '
'
}) .state('access.signin', { url: '/signin', templateUrl: 'partials/signin.html', resolve: { deps: ['uiLoad', function (uiLoad) { return uiLoad.load(['js/controllers/signin.js']); }] }, controller: "signin_ctrl" // signin页面中的controller名字 }) } ]);

main.js

全局的一些比如注销函数,兼容性,兼容移动端,copy就行,

'use strict';

/* Controllers */

angular.module('app')
  .controller('AppCtrl',
    function($rootScope, $scope, $translate, $localStorage,
             $window, $state, call_api, storage) {
      // add 'ie' classes to html
      var isIE = !!navigator.userAgent.match(/MSIE/i);
      isIE && angular.element($window.document.body).addClass('ie');
      isSmartDevice( $window ) && angular.element($window.document.body).addClass('smart');

      // config
      $rootScope.app = {
        getway:'http://localhost:8080',
        name: 'demo',
        version: '1.0',
        // for chart colors
        color: {
          primary: '#7266ba',
          info:    '#23b7e5',
          success: '#27c24c',
          warning: '#fad733',
          danger:  '#f05050',
          light:   '#e8eff0',
          dark:    '#3a3f51',
          black:   '#1c2b36'
        },
        settings: {
          themeID: 1,
          navbarHeaderColor: 'bg-black',
          navbarCollapseColor: 'bg-white-only',
          asideColor: 'bg-black',
          headerFixed: true,
          asideFixed: false,
          asideFolded: false,
          asideDock: false,
          container: false
        }
      }

      function isSmartDevice( $window )
      {
          // Adapted from http://www.detectmobilebrowsers.com
          var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
          // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
          return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
      }

      $scope.logout = function(){
        call_api.get("/api/login/logout", function(data){ // xxd 注销的接口
          if(data.code == 100000){
            $rootScope.global.login = false;
              $rootScope.global.token = '';
            storage.set("QSLH_OW_MANAGER_GLOBAL", $rootScope.global);
            $state.go("access.signin");// xxd
          }
        });
      }
      $scope.maskShow = function () {
          angular.element("#mask").show();
      }
      $scope.maskHide = function () {
          angular.element("#mask").hide();
      }
  });

service.js文件

相当于自定义的方法,或者类,十分方便相当于工具类

(function (angular) {
    'use strict';

    angular.module('app')

        .factory('storage', function () {
            var service = {};

            service.localStorage = window.localStorage;

            service.set = function (key, data) { try { data = JSON.stringify(data); } catch (ex) { } service.localStorage.setItem(key, data); };

            service.get = function (key) { var content = service.localStorage.getItem(key); if (content) { try { return JSON.parse(content); } catch (ex) { } } return content; };

            return service;
        })
        .factory("call_api", function ($rootScope, common_base, $http) {
            var service = { post: function (url, data, callback) { if (common_base.is_function(data)) { callback = data; data = undefined; } $http({ method: 'POST', url: $rootScope.app.getway + url, data: data, }).success(function (data, status, header) { callback(data, header); }).error(function (data, header, config, status) { alert("调用接口失败,请联系管理员"); }); }, get: function (url, callback) { $http({ method: 'GET', url: $rootScope.app.getway + url }).success(function (data, header, config, status) { callback(data); }).error(function (data, header, config, status) { alert("调用接口失败,请联系管理员"); }); } };
            return service;
        }).factory("file_action", function ($rootScope, common_base, $http) {
        var service = { downloadfile: function (url, data, callback) { if (common_base.is_function(data)) { callback = data; data = undefined; } $http({ method: 'POST', url: $rootScope.app.getway + url, data: data, responseType: "arraybuffer" }).success(function (data, status, header) { callback(data, header); }).error(function (data, header, config, status) { alert("文件调用接口失败,请联系管理员"); }); }, uploadfile: function (url,data, callback) { if (common_base.is_function(data)) { callback = data; data = undefined; } $http({ method: 'POST', url: $rootScope.app.getway + url, data: data, headers: {'Content-Type':undefined}, transformRequest: angular.identity }).success(function (data, header, config, status) { callback(data); }).error(function (data, header, config, status) { alert("文件上传调用接口失败,请联系管理员"); }); } };
        return service;
    })
        .factory("common_base", function () {
            var service = { is_function: function (obj) { return (typeof obj == 'function') && obj.constructor == Function; }, format: function () { if (arguments.length == 0) return null; return this.format_by_array(arguments); }, format_by_array: function (args) { if (args.length == 0) return null; var str = args[0]; for (var i = 1; i < args.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, args[i]); } return str; }, is_null: function (exp) { return !exp || typeof(exp) == "undefined"; } }; return service; }); })(window.angular); 

上面的方法或者js文件,你不需要看懂,全部拿出copy就可以使用在项目中,看着github中的例子就可以直接上手,先使用,有了疑惑,再去百度或者请求别人,这样才是正确的做法。有疑问请留言。。

你可能感兴趣的:(web入门)