Angularjs directive 指令复用,指令传参

本文介绍如何在AngularJS中使用自定义指令处理同一页面上的多个元素,通过隔离作用域确保数据正确绑定。同时展示了如何通过HTTP请求动态加载数据并更新视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图这里写图片描述
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;">&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的程序员有所帮助!
如有疑问可以私聊我。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值