AngularJS 自定义directive

一、先写一个directive,注意一下几点

1:名称 shopListView,在html中引用时,名称对应shop-list-view
2:scope为新建,切有个属性为 shopList,在html中引用时,属性对应shop-list
3: showDetail 为采用父scope中的方法,同样在html引用时,属性对应show-detail

举例
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;
                }
            }
        };
    });


二、shopListTemplate.html的定义,注意以下几点:
1:shop in shopList,shopList对应该directive中的scope下的同名属性
2:ng-click=" changeItemSelected(shop)",对应directive中的同名方法
3:ng-click=" showDetail({key:shop})"中,showDetail对应scope下的同名方法,传参为一个map对象,键为‘ key‘字符串,值为’shop‘对象

<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>


三、在html中使用,注意:
1:shop-list-view 名称
2:shop-list 属性
3:show-detail="showDetail(key),show-detail对应scope中的showDetail方法,key为获取的map对应中的键,这里决定了 二.3

<!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>


四、controller定义
angular.module("app", []) 
  .controller('shopCtrl', function ($scope) {
   
   $scope.dataList=[{''seller_id':'xx'}];
 
   $scope.showDetail = function (param) {
        $scope._showModel(
         ...);
    }
});  

你可能感兴趣的:(JavaScript,AngularJ)