angularjs 使用中的積累

信念堤岸發表於2017-04-27

感覺AngularJS最大的優點


1. 改變操作dom的方式
將傳統的JQuery的先選擇元素,再操作的方式改變成了直接對於元素本身的操作。
這依賴於強大的Html Parser的能力和directive靈活。

2. 後端MVC前端化

是的,http://ASP.net MVC, strucs的很多機制,完全可以用AngularJS替代


3. 資料操作
依賴於良好的後端restful介面的配合,完全的變成了早些年pb這樣的資料整合化開發
module是angular中重要的模組組織方式,它提供了將一組內聚的業務元件(controller、service、filter、directive…)封裝在一起的能力。同時module也是我們angular程式碼的入口,首先需要宣告module,然後才能定義angular中的其他元件元素,如controller、service、filter、directive、config程式碼塊、run程式碼塊等。
對於angular.module方法,我們常用的方式有有種,分別為angular.module(‘com.ngbook.demo’, [可選依賴])和angular.module(‘com.ngbook.demo’)。請注意它是完全不同的方式,一個是宣告建立module,而另外一個則是獲取已經宣告瞭的module。

第一章
angularjs簡介:
放棄了ie8,引入了單向資料繫結
刪掉了一些過時的api
2.angularjs 4大核心特性:MVC、模組化、指令系統、雙向資料繫結   
其他特性:依賴注入、過濾器、服務
mvc: Model資料模型層、View檢視層、Controller業務邏輯和控制邏輯
mvc的好處:職責清楚,程式碼模組化

第四章.angularjs開發移動app
一.
1.Native APP 原生app
2.WEB APP    用js html開發用其他的打個包
3.Hybrid APP 混合式式開發 一部分用原生一部分用html的這種 如qq、酷狗音樂
純原生 成本太大開發時間慢、更新慢;webapp操作體驗性不是那麼很好; Hybrid混合式開發呢則是兩者中和,都還行
常用打包工具:
Phonegap、Appcan(國內)、appcelerator

常見web app框架:
jquery       技術棧統一成本低 缺點:低端安卓機存在效能問題
Sencha Touch 各項技術架構很完善  學習成本高
angularjs

第五章 前端自動化測試工具

第二章Angularjs
2.1 angulargis是怎麼樣實現mvc的
    如何使用Control:
   都是由$scope來進行的,在頁面html標籤中加上了ng-app來識別, <button ng-click="save()" >
2.2路由、模組、依賴注入
   一些都是從模組開始的,模組化實現

一。
1.angularjs點選事件跳轉【2017-3-31】
//定義一個控制器
app.controller('addPersonnelCtrl', ['$http', '$location', function ($http, $location) {
    var self = this;
   self.jumpToUrl = function (path) {
        $location.path(path);
    };
}]);
<input ng-click="ctl.jumpToUrl('/app/admin/managePersonnel')" type="button" value="檢視資訊" class="sp-btn-blue sp-radius" />
    self.viewManagePersonnel = function () {        
        self.jumpToUrl('/app/admin/managePersonnel');
    };

2.angularjs的 ui-sref中傳遞引數【2017-3-31】
  例如:路由配置如下:
$stateProvider.state('admin.userList', {
    url: '/listUser?id&role',         //引數必須先在這邊宣告
    templateUrl: requirejs.toUrl('../../user/user_list.html'),    
})
頁面中:
<a ui-sref="admin.userList({id: 1, role: 2})" class="btn">按鈕</a>
在js的指令中,接收 用到了$stateParams
app.controller('retiredCtrl', ['$http', '$stateParams', function ($http, $stateParams) {
    var getID = $stateParams.id; //獲取到編號id
    var getType = $stateParams.type; //獲取到編號id
}]);

3.【2017-04-02】angularjs的ng-model與laydae一起使用 的解決辦法
/**
 * 使用示例
 * <input def-laydate type="text" id="id1" ng-model="startTime"/>
 */
app.directive('defLaydate', function () {
    return {
        require: '?ngModel',
        restrict: 'A',
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attr, ngModel) {
            var _date = null, _config = {};


            // 初始化引數 
            _config = {
                elem: '#' + attr.id,
                format: attr.format != undefined && attr.format != '' ? attr.format : 'YYYY-MM-DD',
                max: attr.hasOwnProperty('maxDate') ? attr.maxDate : '',
                min: attr.hasOwnProperty('minDate') ? attr.minDate : '',
                choose: function (data) {
                    scope.$apply(setViewValue);


                },
                clear: function () {
                    //ngModel.$setViewValue(null);
                }
            };
            // 初始化
            _date = laydate(_config);
            // 模型值同步到檢視上
            //ngModel.$render = function () {
            //    element.val(ngModel.$viewValue || '');
            //};
            // 監聽元素上的事件
            element.on('blur keyup change', function () {
                scope.$apply(setViewValue);
            });
            setViewValue();

            // 更新模型上的檢視值
            function setViewValue() {
                var val = element.val();
                //ngModel.$setViewValue(val);
            }
        }
    }
});


4. ng-show 判斷
<a ng-show="'{{user.STATUS}}'=='未生效'" ui-sref="app.app_install({id:'{{item.ID}}',appid:{{item.APPID}}})" class="ligblue">安 裝</a>
5.指令 directive
<a ui-sref="" toggle-main-menu>首頁</a>
angular.module('app').directive("toggleMainMenu", function() {
  return {
    restrict: "A",
    link: function(scope, elem, attrs) {
      $(elem).click(function() {
        if($(this).next().hasClass('sub-menu') === false) {
          return;
        }
      console.log("click");
      });
    }
  }
});

6,。
          $http({
                method: 'get',
                url: 'json/message.txt',
                data: { info: self.info }
            }).success(function (response) {
                //成功之後,提示 繼續新增,還是檢視資訊
                if (response.success) {
                    special.dialog(response.message);
                } else {
                    special.dialog("新增失敗!");
                }
            });

7.ng-click傳引數
<a ng-click="ctl.deleteWorksheet('{{item.ID}}')" class="sp-color-red">刪除</a>
  var self = this;
  self.deleteWorksheet = function (str) {
        var getID = str;
        alert(getID);        
   }

8.宣告控制器
app.controller('myappCtrl', ['$http', function ($http) {
}]);

9.angularjs中的img 
<img class="sp-upload-photo"  alt="" ng-src="{{ctl.info.photo2}}" />

10.angularjs教程:
10.1. ng-app指令: 標記了AngularJS指令碼的作用域,在<html>中新增ng-app屬性即說明整個<html>都是AngularJS指令碼作用域
10.2. 雙大括號繫結的表示式: AngularJS模板的核心功能——繫結,這個繫結由雙大括號{{}},這個繫結告訴AngularJS需要運算其中的表示式並將結果插入DOM中
10.3. ng-model 指令用於繫結應用程式資料到 HTML 控制器(input, select, textarea)的值。
      ng-init 指令初始化應用程式資料。
10.4. AngularJS 使用$scope 物件來呼叫控制器。在 AngularJS 中, $scope 是一個應用物件(屬於應用變數和函式)。控制器的 $scope (相當於作用域、控制範圍)用來儲存AngularJS Model(模型)的物件。
10.5. AngularJS 過濾器   過濾器可以使用一個管道字元(|)新增到表示式和指令中
      AngularJS 過濾器可用於轉換資料:
10.5.1. currency  格式化數字為貨幣格式。 
<div ng-app="myApp" ng-controller="costCtrl">
數量: <input type="number" ng-model="quantity">
價格: <input type="number" ng-model="price">
<p>總價 = {{ (quantity * price) | currency }}</p>
</div> 
<script>
var app = angular.module('myApp', []);
app.controller('costCtrl', function($scope) {
   $scope.quantity = 1;
   $scope.price = 9.99;
});
</script>
10.5.2. uppercase  格式化字串為大寫
<div ng-app="myApp" ng-controller="personCtrl">
<p>姓名為 {{ lastName | uppercase }}</p>
</div>
10.5.3.  lowercase  格式化字串為小寫。
<div ng-app="myApp" ng-controller="personCtrl">
<p>姓名為 {{ lastName | lowercase }}</p>
</div>
10.5.4. orderBy 過濾器根據表示式排列陣列:
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
 <li ng-repeat="x in names | orderBy:'country'">
   {{ x.name + ', ' + x.country }}
 </li>
</ul>
</div>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
   $scope.names = [
       {name:'Jani',country:'Norway'},
       {name:'Hege',country:'Sweden'},
       {name:'Kai',country:'Denmark'}
   ];
});
10.5.5. 輸入過濾器
<div ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
 <li ng-repeat="x in names | filter:test | orderBy:'country'">
   {{ (x.name | uppercase) + ', ' + x.country }}
 </li>
</ul>
</div>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
   $scope.names = [
       {name:'Jani',country:'Norway'},
       {name:'Hege',country:'Sweden'},
       {name:'Kai',country:'Denmark'}
   ];
});
10.5.6. 自定義過濾器  
        以下例項自定義一個過濾器 reverse,將字串反轉:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.msg = "Runoob";
});
app.filter('reverse', function() { //可以注入依賴
   return function(text) {
            return text.split("").reverse().join("");
   }
});
10.5.7.  常用例項
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 格式化(保留小數)
  {{149016.1945000 | number:2}}
4、currency貨幣格式化
  {{ 250 | currency }}            // 結果:$250.00
  {{ 250 | currency:"RMB ¥ " }}  // 結果:RMB ¥ 250.00
5、filter查詢
  輸入過濾器可以通過一個管道字元(|)和一個過濾器新增到指令中,該過濾器後跟一個冒號和一個模型名稱。
  filter 過濾器從陣列中選擇一個子集
   // 查詢name為iphone的行
  {{ [{"age": 20,"id": 10,"name": "iphone"},
  {"age": 12,"id": 11,"name": "sunm xing"},
  {"age": 44,"id": 12,"name": "test abc"}
  ] | filter:{'name':'iphone'} }}  
6、limitTo 擷取
  {{"1234567890" | limitTo :6}} // 從前面開始擷取6位
  {{"1234567890" | limitTo:-4}} // 從後面開始擷取4位
7、orderBy 排序
 // 根id降序排
 {{ [{"age": 20,"id": 10,"name": "iphone"},
 {"age": 12,"id": 11,"name": "sunm xing"},
 {"age": 44,"id": 12,"name": "test abc"}
 ] | orderBy:'id':true }}


 // 根據id升序排
 {{ [{"age": 20,"id": 10,"name": "iphone"},
 {"age": 12,"id": 11,"name": "sunm xing"},
 {"age": 44,"id": 12,"name": "test abc"}
 ] | orderBy:'id' }} 


11.自定義過濾器
<div ng-app="myApp" ng-controller="myCtrl">
    姓名: {{ msg | reverse }}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.msg = "Runoob";
});
app.filter('reverse', function() { //可以注入依賴,進行反轉
    return function(text) {
        return text.split("").reverse().join("");
    }
});
</script>


11.2. 過濾時間:
      <td ng-bind="ctl.info.BIRTHDAY | date:'yyyy-MM-dd'"></td>