1. 程式人生 > >前端開發框架總結之Angular實用技巧(一)

前端開發框架總結之Angular實用技巧(一)

                              前端開發框架總結之Angular實用技巧(一)

前言:

前一段時間接觸了Angular框架,這是一款非常實用的JS框架,它可以大大減少直接對頁面元素的操作,使複雜功能的實現更簡單。AngularJS有著諸多特性,最為核心的是:MVW(Model-View-Whatever)、模組化、自動化雙向資料繫結、語義化標籤、依賴注入等等。想要真正把Angular的優勢發揮到極致,還是需要轉變傳統前端編碼思路的,更多的把注意力放在資料模型的設計上,更多的運用一些後臺程式設計思想。廢話不多說,直接開始今天的正文。

我專案中使用較多前端UI框架時layui,當初選擇layui主要是因為覺得layui使用簡單。但是把Angular和layui結合起來使用的話,經常會遇到一些表單元素概率性重新整理不出來的情況。究其根本原因無非就是頁面元素載入和js程式碼執行順序的問題,說白了就是layui的js程式碼需要根據自己邏輯處理頁面元素的時候,但是頁面元素還未生成或者載入成功。最常見的場景就是在頁面程式碼使用了ng-repeat,ng-repeat中又有一些需要layui.form.render方法才能刷新出來的元素,這時由於執行render的時機不對就會產生頁面元素概率重新整理不出來的問題。藉此我們引出angular的第一個使用技巧---自定義指令。

  • Angular自定義指令

js程式碼片段

app.directive('onFinishRender',['$timeout','$parse',function($timeout,$parse){
    return {
        restrict: 'A',
        link: function(scope,element,attr){
            if(scope.$last === true){
                $timeout(function(){
                    scope.$emit('ngRepeatFinished');
                    var fun = scope.$eval(attr.onFinishRender);
                    if(fun && typeof(fun) == 'function' ){
                        fun();
                    }
                });
            }
        }
    }
}])

頁面使用指令片段

        <div class="layui-form-item" style="margin-top: 20px">
            <label class="layui-form-label" style="width: 90px;text-align: left;padding: 0;line-height: 35px" >請選擇:</label>
            <div class="layui-input-block" style="width: 296px;margin-left: 100px">
                <select lay-filter="bindFilter" lay-search="">
                    <option value="">直接選擇或搜尋選擇</option>
                    <option value={{x.id}} ng-repeat="x in devices" on-finish-render="deviceLoaded" ng-selected="x.id == device.id" >{{x.name}}-{{x.ip}}</option>
                </select>
            </div>
        </div>

上面的程式碼中我們自定義了一個on-finish-render的指令,這個指令能實現這樣一個功能:在ng-repeat元素載入完成之後,會產生一個ngReapeatFinished事件,同時on-finish-render屬性可以是一個方法名,元素載入完成之後會執行這個方法名對應的方法。我們也可以使用$scope.$on方法來監聽ngReapeatFinished事件,以便加入我們的邏輯。實際專案中我們可以使用app的$rootScope來監聽此事件,統一執行元素重新整理操作。

再聚一個自定義標籤的例子

模板程式碼

<div class="modal-title">
    <div class="title-icon"></div>
      <span>{{title}}</span>
       <a  ng-click="close()"><span class="center_vertical"></span></a>
</div>

js程式碼

app.directive('modalTitle',  function () {
  return {
   restrict: 'EA',
   templateUrl: 'tpls/modal-title.html',
      scope:{
      title:'@',
      close:'&'
      }
   }
  }
);

指令的使用

<modal-title title="我是標題" close="dismissModal()"></modal-title>

利用directive的特性,我們還可以做很多事情,在此列出directive的全部屬性有興趣的同學可以挨個屬性的用法瞭解一下。相關的文件很多,在此就不做細說了。

angular.module('myApp', []) 
.directive('myDirective', function() { 
    return { 
        restrict: String, 
        priority: Number, 
        terminal: Boolean, 
        template: String or Template Function: 
            function(tElement, tAttrs) (...}, 
        templateUrl: String, 
        replace: Boolean or String, 
        scope: Boolean or Object, 
        transclude: Boolean, 
        controller: String or  
        function(scope, element, attrs, transclude, otherInjectables) { ... }, 
        controllerAs: String, 
        require: String, 
        link: function(scope, iElement, iAttrs) { ... }, 
        compile: // 返回一個物件或連線函式,如下所示: 
            function(tElement, tAttrs, transclude) { 
                return { 
                    pre: function(scope, iElement, iAttrs, controller) { ... }, 
                    post: function(scope, iElement, iAttrs, controller) { ... } 
                } 
                // 或者 
                return function postLink(...) { ... } 
           } 
    }; });