AngularJS初級(jí)入門實(shí)踐

Angular

配置

模塊

Angular項(xiàng)目流程: 模塊化(分工合作) + 自動(dòng)構(gòu)建工具(優(yōu)化性能與代碼)

主模塊與分模塊方式開(kāi)發(fā);
最后利用Gulp合并,壓縮,重命名JS;

格式:

//-----------------模塊化開(kāi)發(fā)-------------
ng-app="lagouApp"http://主模塊的名稱 主模塊是整個(gè)程序的作用域
//定義一個(gè)主模塊
var app = angular.module("lagouApp", ["app2", "app3", "app4", "app5"]);
//定義分模塊
  var app4 = angular.module("app4", [])
  //定義分模塊的控制器
  app.controller("footerCtrl", function($scope) {
      //點(diǎn)擊事件
      $scope.link = function() {
          console.log(666);
      };
      $scope.img =['../../img/weui/icon_tabbar.png','../../img/weui/icon_tabbar.png','../../img/weui/icon_tabbar.png']
  });

//-----------------自動(dòng)構(gòu)建工具-----
<!-- 合并后的分模塊 -->
    <script src="dist/js/main.js"></script>
    <!-- 分模塊 -->
    <!-- <script src="controller/headerCtrl.js"></script>
    <script src="controller/swiperCtrl.js"></script>
    <script src="controller/listCtrl.js"></script>
    <script src="controller/footerCrel.js"></script> -->

注意:

angular規(guī)定依附在$scope上的數(shù)據(jù)才能傳遞給視圖

只要$scope定義了,{{}}對(duì)應(yīng)顯示對(duì)應(yīng)的值

比如:$scope=>{{}} $scope.name=>{{name}}
angular表達(dá)式很像js表達(dá)式:它們可以包含文字、運(yùn)算符和變量

指令

內(nèi)置指令

>ng-XX="" //內(nèi)置指令
    ng-app //定義主模塊的作用域
    ng-controller //定義分模塊的控制器
    ng-init //初始化應(yīng)用程序數(shù)據(jù)(定義數(shù)據(jù)放在HTML標(biāo)簽內(nèi))
    ng-click = "function()" //點(diǎn)擊事件執(zhí)行對(duì)應(yīng)的函數(shù)
    ng-bind = "name"http:// ==> 等同于{{name}} 代替表達(dá)式的寫(xiě)法 
    //常用
    ng-model="value"http://雙向綁定(雙方數(shù)值都能互相改變彼此);此指令只能配合input select textarea標(biāo)簽使用
    ng-repeat = " arr in arrays" //"單項(xiàng)數(shù)組 in 整個(gè)數(shù)組"   
    
    ng-show = "bool" //"布爾值" 真則顯示,反之則隱藏 適合頻繁綁定事件的環(huán)境
    ng-if = "bool" //增加/刪除DOM節(jié)點(diǎn)    不適合頻繁綁定事件的環(huán)境;
    ng-class = "{'am-active':page===n}" //ng-class接受的對(duì)象,鍵名是類名,鍵值是布爾值,如果右邊的布爾值為真,那左邊的類就出現(xiàn),反之就隱藏
    
    //其他
    ng-src="{{路徑}}"
    ng-href="{{路徑}}"
    ng-switch="變量"配合ng-switch-when=""

拓展:

指令 作用
ng-app 定義應(yīng)用程序的根元素。
ng-bind 綁定 HTML 元素到應(yīng)用程序數(shù)據(jù)
ng-bind-html 綁定 HTML 元素的 innerHTML 到應(yīng)用程序數(shù)據(jù),并移除 HTML 字符串中危險(xiǎn)字符
ng-bind-template 規(guī)定要使用模板替換的文本內(nèi)容
ng-blur 規(guī)定blur事件的行為
ng-change 規(guī)定在內(nèi)容改變時(shí)要執(zhí)行的表達(dá)式
ng-checked 規(guī)定元素是否被選中
ng-class 指定 HTML 元素使用的 CSS類
ng-class-even 類似 ng-class,但只在偶數(shù)行起作用
ng-class-odd 類似 ng-class,但只在奇數(shù)行起作用
ng-click 定義元素被點(diǎn)擊時(shí)的行為
ng-cloak 在應(yīng)用正要加載時(shí)防止其閃爍
ng-controller 定義應(yīng)用的控制器對(duì)象
ng-copy 規(guī)定拷貝事件的行為
ng-csp 修改內(nèi)容的安全策略
ng-cut 規(guī)定剪切事件的行為
ng-dblclick 規(guī)定雙擊事件的行為
ng-disabled 規(guī)定一個(gè)元素是否被禁用
ng-focus 規(guī)定聚焦事件的行為
ng-form 指定 HTML表單繼承控制器表單
ng-hide 隱藏或顯示 HTML元素
ng-href 為 the<a>元素指定鏈接
ng-if 如果條件為 false移除 HTML元素
ng-include 在應(yīng)用中包含 HTML文件
ng-init 定義應(yīng)用的初始化值
ng-jq 定義應(yīng)用必須使用到的庫(kù),如:jQuery
ng-keydown 規(guī)定按下按鍵事件的行為
ng-keypress 規(guī)定按下按鍵事件的行為
ng-keyup 規(guī)定松開(kāi)按鍵事件的行為
ng-list 將文本轉(zhuǎn)換為列表 (數(shù)組)
ng-model 綁定 HTML 控制器的值到應(yīng)用數(shù)據(jù)
ng-mousedown 規(guī)定按下鼠標(biāo)按鍵時(shí)的行為
ng-model-options 規(guī)定如何更新模型
ng-mouseenter 規(guī)定鼠標(biāo)指針穿過(guò)元素時(shí)的行為
ng-mouseleave 規(guī)定鼠標(biāo)指針離開(kāi)元素時(shí)的行為
ng-mousemove 規(guī)定鼠標(biāo)指針在指定的元素中移動(dòng)時(shí)的行為
ng-mouseover 規(guī)定鼠標(biāo)指針位于元素上方時(shí)的行為
ng-mouseup 規(guī)定當(dāng)在元素上松開(kāi)鼠標(biāo)按鈕時(shí)的行為
ng-non-bindable 規(guī)定元素或子元素不能綁定數(shù)據(jù)
ng-open 指定元素的open屬性
ng-options <select>列表中指定 <options>
ng-paste 規(guī)定粘貼事件的行為
ng-pluralize 根據(jù)本地化規(guī)則顯示信息
ng-readonly 指定元素的readonly屬性
ng-repeat 定義集合中每項(xiàng)數(shù)據(jù)的模板
ng-selected 指定元素的selected屬性
ng-show 顯示或隱藏HTML元素
ng-src 指定元素的src屬性
ng-srcset 指定元素的srcset屬性
ng-style 指定元素的 style屬性 ng-style="{{n.left}}
ng-submit 規(guī)定 onsubmit事件發(fā)生時(shí)執(zhí)行的表達(dá)式
ng-switch 規(guī)定顯示或隱藏子元素的條件
ng-transclude 規(guī)定填充的目標(biāo)位置
ng-value 規(guī)定 input元素的值

Angular內(nèi)置指令DEMO
詳情可參考文檔

坑:臟值檢測(cè)

在雙向數(shù)據(jù)綁定中:
原生/JQ + angular 可能會(huì)導(dǎo)致 臟值檢查機(jī)制失效,從而導(dǎo)致雙向綁定失效;
解決:手動(dòng)刷新或者全部用Angular方法;

服務(wù)

定義:

服務(wù)是一個(gè)函數(shù)或'單例對(duì)象',就相當(dāng)于我們可以在angular程序中封裝好一些方法然后在需要用的時(shí)候 '注入' 到需要用到的地方<span style="color: red">(控制器,自定義服務(wù),自定義指令和自定義過(guò)濾器中)</span>,這樣可以增強(qiáng)我們程序的擴(kuò)展性和復(fù)用性

內(nèi)置服務(wù)

$scope

用來(lái)綁定數(shù)據(jù)模型,是控制器獨(dú)有的服務(wù).控制器中的數(shù)據(jù)需要依賴$scope服務(wù)才能傳遞到View視圖層

$rootScope

是ng-app的作用域范圍,它可以用在兩個(gè)控制器之間傳遞數(shù)據(jù),你可以把它看做ng的全局作用域

$sce

處理html為安全字符的一個(gè)服務(wù) 跟 ng-bind-html 配合

//view
<div ng-bind-html="html"></div>
//model
$scope.html = "<p>Hello Wscat</p>";
$scope.html = $sce.trustAsHtml($scope.html)


$http

Get請(qǐng)求

$http({
    method:"get",
    url:"Oaoafly.php"
    params:{}
})
.then(function(data){
    //成功的回調(diào)
},function(err){
    //失敗的回調(diào)
})

Post請(qǐng)求

    $http({
            method: 'post',
            url: 'http://localhost:8081/search',
            data: {
                "page": $scope.page,
                "pageNum": $scope.pageNum
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            transformRequest: function(obj) {
                var str = [];
                for (var p in obj) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))
                }
                return str.join('&')
            }
        }).then(function(data) {
           console.log(data)//打印服務(wù)端返回的數(shù)據(jù)
        }, function(err) {
            console.log(err)//打印錯(cuò)誤信息
        });

注意點(diǎn):POST請(qǐng)求參數(shù)處理

$filter服務(wù)


$window && $document

  1. $window服務(wù)對(duì)應(yīng)了JS的全局window
  2. $document服務(wù)對(duì)應(yīng)了JS的document,用的時(shí)候注意要這樣用$document[0]

    注意:

    如果需要用到原生JS代碼,最好在前面加上$window有利于解決雙向綁定數(shù)值失效的問(wèn)題;

$location

獲取url的哈希值

    var app = angular.module('app', []);
    app.controller('div', function($scope,$location) {
    $scope.name = 'heightzhang';

    var abc = $location.search({
        "foo": "yipee",
        "abc":"1231"
    
    });  //1.=>設(shè)置哈希值為 : #!?foo=yipee&abc=1231;

    var def = $location.search()
    console.log(def);//2.=>獲取哈希值的結(jié)果為 : {abc:"1231",foo:"yipee"}

});

注意: angular使用 $location服務(wù)比使用 window.location對(duì)象更好。

angular會(huì)一直監(jiān)控應(yīng)用,處理事件變化,window.location 對(duì)象在angular應(yīng)用中有一定的局限性.

$timeout && $interval

  1. $timeout服務(wù)對(duì)應(yīng)了JS的window.setTimeout函數(shù)
  2. $interval服務(wù)對(duì)應(yīng)了JS的window.setInterval函數(shù)
$scope.interval = 0;
$scope.timeout = 0;
$timeout(function(){
    $scope.timeout = 1;
},1000)
$interval(function(){
    $scope.interval++
},1000)

過(guò)濾器

語(yǔ)法

過(guò)濾器可以通過(guò)一個(gè)管道字符(|)和一個(gè)過(guò)濾器添加到表達(dá)式中

{{num|過(guò)濾器的名字:參數(shù)}}

內(nèi)置過(guò)濾器

filter methods
currency currency:"貨幣符號(hào)"
uppercase uppercase大寫(xiě)
lowercase lowercase小寫(xiě)
filter 接受一個(gè)對(duì)象,一般配合ng-repeat
orderBy 接受兩個(gè)參數(shù),第一個(gè)是要排序的鍵值,第二個(gè)是個(gè)布爾值
limitTo 可以用于分頁(yè),第一個(gè)參數(shù)就是截取的長(zhǎng)度,第二個(gè)是截取的位置,可以用于截取字符串和數(shù)組
json 就是把對(duì)象轉(zhuǎn)為字符串顯示,一般用于調(diào)試頁(yè)面數(shù)據(jù)
date 接受時(shí)間戳格式,處理成常用的時(shí)間格式
number 精確到就是小數(shù)點(diǎn)后幾位

Angular內(nèi)置過(guò)濾器

$fiter服務(wù)

這個(gè)服務(wù)可以注入到過(guò)濾器或者控制器里面

在AngularJS的controller, service或者driective中使用filter

$filter("過(guò)濾器名字")("處理的數(shù)據(jù)","過(guò)濾器的參數(shù)")

前端篩選組合

orderBy和filter和limitTo 排序 搜索 分頁(yè)

orderBy:A:B
接收兩個(gè)參數(shù)
a是要排序的對(duì)象,b是個(gè)布爾值

true為降序 ,false為升序;

#Bug 數(shù)字排序; 存入數(shù)據(jù)庫(kù)類型要是int;
實(shí)現(xiàn)升序或降序

filter:A|filter:B 或者接收一個(gè)對(duì)象 實(shí)現(xiàn)一級(jí)搜索或者二級(jí)搜索

limitTo:A:B a數(shù)量,b索引值 截取字符串或者數(shù)組,實(shí)現(xiàn)分頁(yè)效果;

注意:過(guò)濾器支持鏈?zhǔn)秸{(diào)用

路由

第一種:原生路由

引入../js/angular-route.js

var app = angular.module('routeApp',['ngRoute','routes','controller','directives']);
    //路由
      //建立路由模塊
    var routes = angular.module("routes",[]);
      //1.配置路由Url
    routes.config(function($routeProvider){
        $routeProvider.when("/home",{
            templateUrl:"template/home.html"
        }).when("/detail",{
            templateUrl:"template/detail.html"
        })
        //3.路由傳參
        .when("/detail/:id/:skill",{
            controller:"ulCtrl"  //建立子控制器
            templateUrl:"template/detail.html"
        })

        //2.默認(rèn)重定向的路由路徑(默認(rèn)值設(shè)定)
        .otherwise({
                redirectTo: '/home'
        })
        // 注意:傳參要設(shè)置兩個(gè)路由,一個(gè)模版,一個(gè)傳參路由;
    })

    //建立控制器模塊;
    var controller = angular.module('controller',[]);
     //配置控制器
    controller.controller('ulCtrl',function($scope,$routeParams){
        $scope.name = 'heightzhang'
        //3.路由傳參  ,打印傳遞的url參數(shù)
        console.log($routeParams)
    });
    
    controller.controller('aCtril',function($scope){
        $scope.name = "zhangggao";
        $scope.url = "#!/home?id=5"
    });

    //4.建立組件化模版
    var directives = angular.module("directives", []);
        directives.directive("xheader", function() {
            return {
                template: "<header>今日頭條</header>"
            }
        });

第二種:UI路由

引入../js/angular-ui-router.js

//建立主模塊
    var app = angular.module('uirouterApp',['ui.router']);
    //配置路由
    app.config(function($stateProvider,$urlRouterProvider){
        //設(shè)置默認(rèn)路由;
        $urlRouterProvider.when('', '/index');
     //Angular
        //一層
        $stateProvider.state("index",{
            url:"/index",
            templateUrl:"1.2template/angular.html"
        })
        //"."表示從屬關(guān)系
        //二層
        .state("index.a",{
            url:"/a",
            templateUrl:"1.2template/angular2.html"
        })
        //三層
        .state("index.a.aa",{
            url:"/aa",
            templateUrl:"1.2template/angular3.html"
        })
     //Jquery
        .state("home",{
            url:"/home",
            templateUrl:"1.2template/jquery.html"
        })
        .state("home.a",{
            url:"/a",
            templateUrl:"1.2template/jquery2.html"
        })
        .state("home.a.aa",{
            url:"/aa",
            templateUrl:"1.2template/jquery3.html"
        })
     //傳參數(shù)
        .state("detail",{
            url:"/detail/:id",
             //設(shè)置子控制器;
            controller:"detailCtrl",
            
            templateUrl:"1.2template/detail.html"
        })
    });

    //接收url參數(shù)
    app.controller("detailCtrl",function($state){
            console.log($state.params)
    });

    //注意 :路由隨便寫(xiě)也能進(jìn)入網(wǎng)頁(yè),是不會(huì)報(bào)錯(cuò)的,只是你需要打印的東西無(wú)法打印出來(lái);

我們開(kāi)發(fā)中一般使用UI路由,UI路由可以嵌套;原生路由不支持嵌套

自定義過(guò)濾器

適合:修飾的復(fù)用;

//#自定義無(wú)參數(shù)過(guò)濾器:
    //比如:過(guò)濾HTML結(jié)構(gòu)  
    //格式:
    <div ng-bind-html="html|htmled"></div>
    app.filter("htmled", function($sce) {
        return function(input) {
            //input => 需要過(guò)濾的數(shù)據(jù)處理成新的數(shù)據(jù)
            return $sce.trustAsHtml(input)
        }
    })

//#自定義有參數(shù)過(guò)濾器:
    //適用在需要設(shè)置第二個(gè)數(shù)據(jù)才可以過(guò)濾的情形下;
    //比如:高亮搜索內(nèi)容(搜索內(nèi)容為需要高亮的部分)
    <div ng-bind-html="html|highlight:search"></div>
    app.filter("highlight", function() {
        return function(input, search) {
            console.log(search)
            console.log(input)
            var arr = input.split(search);
            var output = arr.join("<span style='color:red'>" + search + "</span>")
            return output;
        }
    })

自定義服務(wù)

適合:方法的復(fù)用

//主模塊
var app = angular.module('app', ['div','service']);
//分模塊
var div = angular.module('div', []);
//分模塊控制器
div.controller('divCtrl', function($scope,tool,abc,exchange) {
    $scope.name = "heightzhang";
   console.log(tool); //共享自定義服務(wù);
   console.log(abc);  //自定義服務(wù)引用其他服務(wù)
   console.log(exchange.name) //自定義服務(wù)通信, 傳遞數(shù)據(jù);
});

//服務(wù)模塊;  1.主模塊引入服務(wù)'依賴', 所有的分模塊 通過(guò)注入該新服務(wù),可以共享新服務(wù);

var service = angular.module('service', []);

service.service('tool', function() {
    return {
        add: function(a, b) {
            return a + b
        }
    }
});

//2.第二個(gè)自定義服務(wù)中使用之前自定義服務(wù)或者內(nèi)置服務(wù)的時(shí)候;用傳參方法;
service.service('abc', function($http) {   
    return {
       tool:$http
    }
});
//3.service作為通信 傳遞數(shù)據(jù);
service.service('exchange',function(){
    return {
        name:'heightzhang'
    }
})

其他自定義服務(wù);

  1. value就是一個(gè)簡(jiǎn)單的可注入的值
  2. service是一個(gè)可注入的構(gòu)造器
  3. factory是一個(gè)可注入的方法
  4. decorator可以修改或封裝其他的供應(yīng)商,當(dāng)然除了constant
  5. provider是一個(gè)可配置的factory

自定義組件/指令

適合:組件適合HTML結(jié)構(gòu)的復(fù)用

關(guān)于自定義的四種狀態(tài)

自定義組件

//自定義了一個(gè)<xheader></xheader>組件
app.directive("xheader", function() {
    return {
        restrict: "E",   //元素
        template: `
            <div>
                <header ng-transclude></header>
                <p>Hello {{name}}</p>
            </div>
        `
    }
})

自定義指令

//自定義了一個(gè)<div ng-header></div>的指令
app.directive("ngHeader", function() {
    return {
        restrict: "A",   //屬性
        template: `
            <div>
                <header ng-transclude></header>
                <p>Hello {{name}}</p>
            </div>
        `
    }
})

自定義類指令

//自定義了一個(gè)<div class = "ng-header"></div>類的指令
app.directive("ngHeader", function() {
    return {
        restrict: "C",   //類
        template: `
            <div>
                <header ng-transclude></header>
                <p>Hello {{name}}</p>
            </div>
        `
    }
})

ECMA:

value
element 元素,標(biāo)簽
attribute 屬性
class
m 注釋

Tips:

  1. restrict:ECMA或者不寫(xiě),則默認(rèn)允許呈現(xiàn)四種狀態(tài);
  2. template(模版)的規(guī)范,建議先定義一個(gè)外圍容器包圍;
  3. 控制器可以理解為唯一的ID, <span style="color: red">控制器不能去復(fù)用</span>;

replace

true:組件的自定義的標(biāo)簽名會(huì)消失,模版的div結(jié)構(gòu)出現(xiàn);

true的好處:對(duì)一些不兼容自定義表情的瀏覽器有好處;

false:組件的自定義標(biāo)簽名出現(xiàn),模版的div結(jié)構(gòu)也出現(xiàn),
false的好處:可以方便我們進(jìn)行分組管理這些組件;

replace默認(rèn)值為false

controller :組件內(nèi)部自身的控制器作用域;提供給template模版使用;

transclude :true 組件支持嵌入

replace \ controller transclude 簡(jiǎn)單代碼如下:

<xheader><p>新聞</p></xheader>

app.directive("xheader", function() {
    return {
        restrict: "ECMA",
        //組件自定義標(biāo)簽名出現(xiàn)
        replace: false,
        //組件支持嵌入<p>新聞</p>嵌入到模版<header ng-transclude></header>里面
        transclude: true,
        //組件的子控制器,給template模版使用
        controller: function($scope, $http) {
            $scope.name = "laoyao"
        },
        template: `
            <div>
                <header ng-transclude></header>
                <p>Hello {{name}}</p>   //子控制器的作用域是該模版區(qū)域;
            </div>
        `
    }
})

link子控制器:

scope,ele,attr
注意:Controller與scope的區(qū)別:兩者區(qū)別不大,我們開(kāi)發(fā)一般會(huì)選用link;

app.directive("xheader", function($http) {
        return {
            //View
            template: `<div>
                <ul>
                    <li ng-repeat="arr in arrs track by $index">{{arr}}</li>
                </ul>
                <button ng-click="loadMore()">{{isShow}}</button> //觸發(fā)事件
            </div>`,
            //Contrl
                 //link 是組件的控制器 scope是存放該組件的數(shù)據(jù)模型model;
            link: function(scope, ele, attr) {
                //Model
                //--------1.scope----------
                scope.arrs = [];
                scope.loadMore = function() {
                    //請(qǐng)求后端數(shù)據(jù)返回給模版
                    $http({
                        method: "GET",
                        url: "http://localhost:81/1702/angular/test.php"
                    }).then(function(data) {
                        console.log(data)
                        scope.arrs = scope.arrs.concat(data.data.arrs)
                });

                //------2.ele ----jQlite----------
                console.log(ele)
                ele.on("click",function(){
                        alert("hello")
                });

                // ----3.attr ----------
                console.log(attr)  //獲取xheader上的attr屬性,有利于通過(guò)JQlite改變?cè)鹊腶ttr值;   
            }
        }
})

匯:控制器之間通信數(shù)據(jù)的方法

1.Angular事件廣播

2.$rootScope

3.Cookies和本地存儲(chǔ)

4.基于服務(wù)器Service通信數(shù)據(jù)

5.Angular基于$window的數(shù)據(jù)通信

6.路由傳參(跨頁(yè)面跨路由的情況)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容