2015年8月28日 星期五

介紹Angular的Directive

 不少人已經知道Directive的好處,可以在抽出共同的元素,但這是屬於靜態的頁面,另一種情況是希望控制事件放在Directive ,例如有一個下拉式選單,可以自動帶出所有診所的名稱,我們只要呼叫自訂的元素,就可以使用這個下拉式選單,我們就能重複使用元件而不是畫面。

一、建立網頁的範本

檔名: showClinicMenu.js

function showClinicMenu(app) {
var templateForm = '<input type="hidden" id={{name}}>';
templateForm += "<input class='form-control' id={{textname}}  ng-model='clinicName' type='text' ng-change='showClinicMenu(clinicName)'>";
    templateForm += "<div class='list-group'>";
    templateForm += "<a href='#' class='list-group-item'  ng-click='setClinicID(clinic.clinicIndex,clinic.clinicName)' ng-repeat='clinic in listClinics'>";
    templateForm += "{{clinic.clinicName}}";
    templateForm += "</a>";
    templateForm += " </div>";
}

    為了將某些元素抽出為共同的元素時,某些欄位名稱要由外部傳進來,所以要呼叫Angular的語法{{}},然後再由Angularcontroller決定變數的值,如果有相關的事件觸發,也能呼叫ng-click呼叫Angularcontroller的事件。

二、建立directive元素

function showClinicMenu(app) {
var templateForm = “<input t>……..”  //網頁的範本… 上面已說明過… 暫時跳過
app.directive("showclinicmenu", function () {
        return {
                restrict: 'E',               
                template: templateForm,
                controller: function ($scope, $attrs, $http) {
                    $scope.name = $attrs.name;  //對應外部的屬性name
                    $scope.textname = $attrs.textname; //對應外部的屬性textname
                    $scope.showClinicMenu = function myfunction(clinicName) {
                        $http.get('../api/ApiTest/listClinics/' + clinicName).then(function (value) {
                            $("#" + $attrs.name).empty();
                            $scope.listClinics = value.data;
                        });
                    }
                    $scope.setClinicID = function (clinicIndex, clinicName) {
                        $scope.listClinics = null; //清空資料
                        $scope.clinicName = clinicName;
                        $("#" + $attrs.name).val(clinicIndex);
                    }
                },
        }
});
}; //end showClinicMenu

    directive中需要用到Controller,要把屬性放在return {}範圍中,在controller中注入需要的元件$scope, $attrs, $http所以在範本建立的變數,就可以在controller的範圍中做變數宣告以及事件宣告,但是如果想外部傳入參數到controller 怎麼辦請大家耐心往下看吧… 

三、呼叫directive元素

<div class="form-group">
     <label>診所名稱</label>
     <showclinicmenu name="editClinicIndex" textname="editClinicName"></showclinicmenu>
</div>
<script src="~/Scripts/directive/showClinicMenu.js"></script>  //引入使用 directive 函式
<script>
var app = angular.module(modelName, []);;
showClinicMenu(app);  //呼叫相關的函式
</script>

不知道大家對 $attrs是否陌生? 這也是最近作者才發現到另一個好用的功能,當我們在用directive時是否需要傳遞參數進來,但又不知道怎麼做? $attrs 就是連結directiveView之間的連結,以上的範例是directive自已建立的Element,但多了兩個屬性(name, textname),原來我們在controller 看見的 $attr ,就可以把值傳入到directivecontroller

app.directive("showclinicmenu", function () {
        return {
                restrict: 'E',              
                controller: function ($scope, $attrs, $http) {
                    $scope.name = $attrs.name;  //對應外部的屬性name
                    $scope.textname = $attrs.textname; //對應外部的屬性textname                  
      }
});

    看完以上的範例後… 各位有更進一步的瞭解Angular 了嗎?  雖然Angular 提出不少方便的小功能,但還是要親身感受才能瞭解它的用意… 希望大家還喜歡我這篇文章,謝謝大家。

Angular另外補充:

l   如何將ng-model設成動態產生的變數名稱,以示簡易示範教學

步驟一: 建立空陣列,如果有預設值可以呼叫foreach迴圈,逐一填入對應值
$scope.dynamic = {}; //用來放置每個no-model 動態值   
angular.forEach(listAllBugs, function (bug, key) {
$scope.statusOptions = ["未完成", "已完成", "會議討論", "退回"];
                    var statusIndex =$scope.statusOptions (bug.status);
                    $scope.dynamic[bug.ikey] = options[statusIndex];
                    $scope.dynamic['estimate_' + rowIndex] = bug.estimatedDate;  //依序填入預設值
                    rowIndex++;
  })

步驟二:ng-model的命名方式:空陣列名稱[‘字串_+$index]
<tr ng-repeat-start="bug in listAllBugs|filter:searchReleaseText" class="active">
<input type="date" class="datepicker form-control"
ng-model="dynamic['estimate_'+ $index]"
id="estimate_{{::bug.ikey}}" value="{{dynamic['estimate_'+ $index]}}" />
 </tr>
以陣列方式將『字串和索引值』就能變成ng-model獨一無二的變數名稱,所以後續取值時,就要以迴圈方式,逐一取出變數值…