AngularJs 筆記

初識

directive 指令

  1. ng-app 初始化一個AngularJs應用程序(經過一個值(好比 ng-app="myModule")鏈接到代碼模塊。)
  2. ng-init 初始化應用程序數據(通常不用)
  3. ng-model 把元素值綁定到應用程序(mvvm的雙向綁定)
  4. ng-bind 將應用程序數據綁定到html視圖
  5. 表達式 {{}} 功能相似 ng-bind,但更普遍的用途html

    <!DOCTYPE html>
     <html lang="zh-cn">
     <head>
     <meta charset="utf-8">
     <script src="angular.min.js"></script> 
     </head>
     <body>
     <div ng-app="" ng-init="firstName='John'">
    
     <p>在輸入框中嘗試輸入:</p>
     <p>姓名: <input type="text" ng-model="firstName"></p>
     <p>你輸入的爲: {{ firstName }}</p>
     <p>你輸入的爲: <span ng-bind="firstName"></span></p>
     </div>
     </body>
     </html>
  6. ng-repeat 重複一個html元素(循環)
  7. 自定義指令json

    mainApp.directive('focus', function () {
        return {
          link: function (scope, element, attrs) {
            element[0].focus();
          }
        };
      });
  8. 其餘經常使用指令
    ng-show,ng-hide,ng-class,ng-view,ng-switch, ng-if, ng-options,ng-disabled,ng-click,ng-include="''"(須要引號,跨域要設置白名單)api

表單驗證

狀態信息

<form ng-app="" name="myForm">
        Email:
        <input type="email" name="myAddress" ng-model="text">
        <span ng-show="myForm.myAddress.$error.email">不是一個合法的郵箱地址</span>
    </form>

    <p>提示信息會在 ng-show 屬性返回 true 的狀況下顯示。</p>

樣式切換

ng-model 指令根據表單域的狀態添加/移除如下類跨域

  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine

做用域scope

$scope.$watch('passw1',function() {$scope.test();});數組

過濾器filter

  1. uppercase,lowercase 大小寫轉換瀏覽器

    {{ "lower cap string" | uppercase }}   // 結果:LOWER CAP STRING
     {{ "TANK is GOOD" | lowercase }}      // 結果:tank is good
  2. date 格式化服務器

    {{1490161945000 | date:"yyyy-MM-dd HH:mm:ss"}} // 2017-03-22 13:52:25
  3. number 格式化(保留小數)app

    {{149016.1945000 | number:2}}
  4. currency貨幣格式化mvvm

    {{ 250 | currency }}            // 結果:$250.00
     {{ 250 | currency:"RMB ¥ " }}  // 結果:RMB ¥ 250.00
  5. limitTo 截取ide

    {{"1234567890" | limitTo :6}} // 從前面開始截取6位
     {{"1234567890" | limitTo:-4}} // 從後面開始截取4位
  6. 查找、排序、自定義過濾

    <body ng-app="myApp">
     <div ng-controller="myCtrl">
         <div ng-bind="myName  | uppercase"></div> <!--uppercase轉換成大寫-->
         <div class="" ng-bind="money | currency : '¥'"> </div><!--currency 過濾器將數字格式化爲貨幣格式-->
         <div class="" ng-repeat="v in city | orderBy:'id'">
             <p ng-bind="v.name"></p>
         </div><!--orderBy 過濾器根據表達式排列數組-->
    
         <div class="" ng-repeat="v in city | orderBy:'-id' | filter : '上海'">
             <p ng-bind="v.name" style="color:red;"></p>
         </div>
         <!--orderBy 過濾器根據表達式排列數組   默認正序asc,倒序添加-負號-->
         <!--filter 過濾器根據表達式過濾不包含過濾器中的內容-->
    
         <!--自定義過濾器aa-->
         <div class="" ng-bind="myName | reverse" style="color:blue;"></div> 
         <div class="" ng-bind="myName | reverse:true" style="color:blue;"></div>            
     </div>
     <script>
     angular.module('myApp',[]).controller('myCtrl',function($scope){
         $scope.myName="Dhx";
         $scope.money=100;
         $scope.city=[
             {"id":"1","name":"福建"},
             {"id":"2","name":"廣東"},
             {"id":"5","name":"上海"},
             {"id":"4","name":"北京"},
             {"id":"3","name":"四川"}
         ]
     }).filter('reverse',function(){ 
         return function(input, uppercase){
                          input = input || '';
                          var out = input.split("").reverse().join("");
                          if (uppercase) {
                          out = out.toUpperCase();
                          }
              return out;
         }
     })
     </script>
     </body>

服務Service

$location ,$http(不能跨域) , $timeout, $interval

用provider自定義一個服務

(1)

var mainApp = angular.module('mainApp', []);
mainApp.config(function($provide) {
    $provide.provider('CalcService', function() {
    this.$get = function() {
        var factory = {};  
     
        factory.square = function(a) {
            return a * a; 
        }
        return factory;
    };
    });
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(2)

var mainApp = angular.module('mainApp', []);
mainApp.config(function($provide) {
    $provide.factory('CalcService', function() {
            var factory = {};  
     
            factory.square = function(a) {
                return a * a; 
            }
            return factory;
    });
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(3)

var mainApp = angular.module('mainApp', []);
mainApp.config(function($provide) {
    $provide.factory('CalcService', function() {
        return function(a) {
            return a * a; 
        };
    });
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService($scope.number);
    }
 });

用factory自定義一個服務

(1)

var mainApp = angular.module('mainApp', []);
mainApp.factory('CalcService', function() {
    var factory ={};
    factory.square = function(a) {
        return a * a; 
    }
    return factory;
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(2)

var mainApp = angular.module('mainApp', []);
mainApp.factory('CalcService', function() {
        return function(a) {
            return a * a; 
        }
    });

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService($scope.number);
    }
 });

用service自定義一個服務

(1)

var mainApp = angular.module('mainApp', []);
mainApp.service('CalcService', function(){
    this.square = function(a) {
        return a * a; 
    }
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(2)

var mainApp = angular.module('mainApp', []);
mainApp.service('CalcService', function(){
    return function(a) {
        return a * a; 
    }
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService($scope.number);
    }
 });

依賴注入

value,factory,service,provider,constant

select


Api

  • angular.lowercase(a) 轉換字符串爲小寫
  • angular.uppercase(a) 轉換字符串爲大寫
  • angular.isString(a) 判斷給定的對象是否爲字符串,若是是返回 true。
  • angular.isNumber(a) 判斷給定的對象是否爲數字,若是是返回 true。
  • angular.isFunction(a)
  • angular.extend(a,b) 從b對象複製全部屬性和函數到a.
  • angular.copy(a),angular(a,b) 拷貝一個副本
  • angular.isObject(a)
  • angular.isArray(a)
  • angular.forEach(object,function(value,key){}); angular.forEach(myArray,function(value,index){})
  • angular.isDefined(a)
  • angular.isUndefined(a)

路由

http://runoob.com/#/first
http://runoob.com/#/second

對服務器而言它們是同一個連接,AngularJS路由就經過「 # + 標記」幫助咱們區分不一樣的邏輯頁面並將不一樣的頁面綁定到對應的控制器上。

  1. 載入了實現路由的 js 文件:angular-route.js。
  2. 包含了 ngRoute 模塊做爲主應用模塊的依賴模塊。

    angular.module('routingDemoApp',['ngRoute'])
  3. 使用 ngView 指令。

    <div ng-view></div>//該 div 內的 HTML 內容會根據路由的變化而變化。
  4. 配置 $routeProvider,AngularJS $routeProvider 用來定義路由規則。

    module.config(['$routeProvider', function($routeProvider){
         $routeProvider
             .when('/',{template:'這是首頁頁面'})
             .when('/computers',{template:'這是電腦分類頁面'})
             .when('/printers',{template:'這是打印機頁面'})
             .otherwise({redirectTo:'/'});
     }]);

$routeProvider.when

$routeProvider.when(url, {
    template: string,
    templateUrl: string,
    controller: string, function 或 array,
    controllerAs: string,
    redirectTo: string, function,
    resolve: object<key, function>
});
  • template:若是咱們只須要在 ng-view 中插入簡單的 HTML 內容,則使用該參數:
  • templateUrl: 若是咱們只須要在 ng-view 中插入 HTML 模板文件,則使用該參數:

    $routeProvider.when('/computers', {
    templateUrl: 'views/computers.html',
    });

  • controller: function、string或數組類型,在當前模板上執行的controller函數,生成新的scope。
  • controllerAs: string類型,爲controller指定別名。
  • redirectTo: 重定向的地址。
  • resolve: 指定當前controller所依賴的其餘模塊。

猜想(待確認):

  1. 一個應用能夠有多個模塊,但在頁面上只能有一個ng-app指令,一個模塊能夠有多個controller
  2. 若是html是視圖,JavaScript代碼中應該有一個自動構建的對應的viewModel
  3. 每一個controller對應着一個scope。controller與controller之間相關隔離,經過rootScope共享數據。
    經過在controller中修改scope,也就在修改viewModel,進而也就修改了view,由於view和viewModel是自動同步的,
  4. $XX表明這是一個應用對象,如$scope, $rootScope,$valid,$dirty,$touched,$error等, $符號不能缺失

筆記 (待整理)

  1. var todoApp = angular.module("todoApp",[]);其中第二個參數是一個由所依賴模塊構成的數組,換言之在應用中是能夠存在多個模塊的。
    1. var todoApp = angular.module("todoApp");則是查找已定義的模塊todoApp
  2. 瀏覽器插件batarang
  3. todoApp.run(function($http){$http.get("todo.json").then(function(data){model.items=data;})});run方法會在AngularJs執行完初始化設置後容許一次。
  4. AngularJs自帶一個裁剪版的jQuery,叫作jqLite,而若是頁面中引入了jQuery,AngularJs會自動檢測到並優先使用jQuery代替jqLite。
  5. 規則
    1. 視圖邏輯僅爲顯示準備數據,永遠不該該修改模型。
    2. 控制器邏輯永遠都不該該直接增刪改模型中的數據。
    3. 客戶端永遠都不該該直接訪問數據存儲。
  6. JS中的對象操做

    var myData = {name:"name",weather:"weather"};
     //判別類型
     console.log(angular.isObject(myData)) //true
     //遍歷
     angular.forEach(myData, function(value,key){
         console.log("name:"+key+", value:"+value);
     });
    
     //擴展
     var myExtendObject = {city:"london"};
     angular.extend(myExtendObject,myData);
     console.log(myExtendObject.weather);
     //複製
     var dataCopy = angular.copy(myData);
     console.log(dataCopy.weather);
     //刪除屬性或方法
     delete myData.name;
     console.log(myData.name) // undefined
     //判別是否擁有屬性
     var hasName = "name" in myData;
     console.log(hasName) // false
     console.log("weather" in myData)//true
相關文章
相關標籤/搜索