效果图
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:330px;">'+
'<span class="r" style="margin-top:4px;width:120px;"> '+
'<span style="vertical-align: 12px;"> {{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的程序员有所帮助!
如有疑问可以私聊我。