1. 程式人生 > >Angularjs directive 指令複用,指令傳參

Angularjs directive 指令複用,指令傳參

效果圖這裡寫圖片描述
html 同一個頁面使用多次指令集,傳入不同的引數

<select-option title="測試2的名字" group="sex" >
</select-option>

<select-option title="測試1的名字" group="sex1">       
</select-option>

js 指令

app.directive('selectOption', function($http){
    return{
        restrict:'E',
        scope :true ,
        link:function
(scope, element, attrs) {
scope.title = attrs.title; scope.group = attrs.group; scope.list = attrs.group; var data = { 'groupName':attrs.title }; scope.ceshi = function(a){ alert(a); }; $http.
post('/datadicItem/findItemsByGroupName',data, postCfg) .success(function(resp){ // debugger scope.list = resp; console.log(scope.list); }); }, template:'<div style="text-align:center;height:330
px;">'+ '<span class="r" style="margin-top:4px;width:120px;"> '+ '<span style="vertical-align: 12px;">&nbsp;&nbsp;{{title}}'+ '<select style="margin-left:5px;"'+ 'ng-model="group"'+ 'ng-change="ceshi(group)"'+ 'ng-options="act.id as act.itemname for act in list">'+'<option value="">'+'--請選擇--'+'</option>'+ '</select>'+ '</span>'+ '</span>'+ '</div>', replace:true, }; });

解釋
html 頁面內 title 與 group的引數傳入指令集內,指令集通過 attrs獲取傳入的引數,然後執行http 呼叫後臺介面獲取資料展示到頁面。由於頁面內有兩個指令,並且傳入的引數不同,所以需要隔離作用域才能防止這兩個指令從後臺獲取的資料混淆。隔離作用域的關鍵程式碼:scope :true 或者 scope :{}
補充
ceshi()方法是可以顯示select選中元素的id。
希望對學習Angularjs的程式設計師有所幫助!
如有疑問可以私聊我。