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

一、写一个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:名称 shopListView,在html中引用时,名称对应shop-list-view
2:其scope是独立,打破了从scope的继承链。其内有属性为 shopList,“=”表示该属性值与父scope中的同名属性双向绑定。在html中引用时,属性写做shop-list
3: showDetail ,“&”表示其可以调用父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 shopList,shopList对应该directive中的scope下的同名属性
2:ng-click=" changeItemSelected(shop)",对应directive中的同名方法
3:ng-click=" showDetail({key:shop})"中,showDetail对应scope下的同名方法,传参为一个map对象,键为‘ key‘字符串,值为’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提供(也就是 shopCtrl提供),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‘,无所谓


参考链接
http://www.w3ctech.com/topic/1612
http://hudeyong926.iteye.com/blog/2072204

猜你喜欢

转载自v7sky.iteye.com/blog/2302246