【AngularJS系列】 自定义列表展示directive

本文介绍了一个具体的AngularJS指令示例,包括如何定义自定义指令、设置独立作用域及属性绑定,同时还演示了如何在HTML中使用这些指令,并与父控制器进行交互。

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

一、写一个directive

module.directive('shopListView, function () {
return {
restrict: 'E',
templateUrl: "/xxx/shopListTemplate.html",
scope: {
shopList: '=',
showDetail : '&'
},
link: function (scope, element, attrs) {
scope.changeItemSelected = function (item) {
item.selected = !item.selected;
}
}
};
});

注意以下几点
1:名称 [b]shopListView[/b],在html中引用时,名称对应shop-list-view
2:其scope是独立,打破了从scope的继承链。其内有属性为[b]shopList[/b],“=”表示该属性值与父scope中的同名属性双向绑定。在html中引用时,属性写做shop-list
3:[b]showDetail[/b] ,“&”表示其可以调用父scope中的方法,同样在html引用时,属性对应show-detail

二、shopListTemplate.html的定义

<div ng-repeat="shop in shopList" class="product-item" ng-class="{'selected': shop.selected}">
<div class="ibox-content product-box" ng-click="changeItemSelected(shop)">
<span>店铺ID:{{shop.seller_id}}</span>

<button type="button" class='btn btn-xs btn-primary' ng-click="showDetail({key:shop})">详情</button>
</div>
</div>
</div>

注意以下几点
1:shop in [b]shopList[/b],shopList对应该directive中的scope下的同名属性
2:ng-click="[b]changeItemSelected[/b](shop)",对应directive中的同名方法
3:ng-click="[b]showDetail[/b]({key:shop})"中,showDetail对应scope下的同名方法,传参为一个map对象,键为‘[b]key[/b]‘字符串,值为’shop‘对象。通过这样的方式,其效果就是能够将directive中独立scope中的对象,通过函数调用,传递到父controller中

三、在html中使用


<!DOCTYPE html>
<html ng-app="app">
<head>
</head>
<body>
<div ng-controller="shopCtrl">
<shop-list-view shop-list="dataList" show-detail="showDetail(key)"> </shop-list-view>
</div>

<script src="/angular.min.js"></script>
...
</body>

注意以下几点
1:shop-list-view 名称
2:shop-list 属性
3:show-detail="showDetail(key),show-detail对应scope中的showDetail方法,且该方法要由父scope提供(也就是[b]shopCtrl[/b]提供),key为map对应中的键,参考二.3

四、定义controller
angular.module("app", []) 
.controller('shopCtrl', function ($scope) {

$scope.dataList=[{''seller_id':'xx'}];

$scope.showDetail = function (param) {
$scope._showModel(
...);
}
});

注意以下几点
1:showDetail = function (param) ,参数命名’param‘,无所谓


参考链接
[url]http://www.w3ctech.com/topic/1612[/url]
[url]http://hudeyong926.iteye.com/blog/2072204[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值