自定义指令实例

var app = angular.module("app",[]);
    app.controller("ctrl", function ($scope) {
        $scope.title = "点击展开";
        $scope.text = "这是内部内容";
        $scope.list = [{ title: "标题1", text: "内容1" }, { title: "标题2", text: "内容2" }, { title: "标题3", text: "内容3" }];
    })
    app.directive('acc', function () {
        return {
            transclude: true,
            template: '<div ng-transclude></div>',
            controller: function () {
                var expanders = [];
                this.got = function (select) {
                    angular.forEach(expanders, function (expander) {
                        if (select != expander) {
                            expander.showMe = false;
                        }
                    });
                }
                this.add = function (expander) {
                    expanders.push(expander);
                }
            }
        }
    });
    app.directive('expander', function () {
        return {
            replace: true,
            transclude: true,
            require: '^?acc',
            template: '<div>'
            + '<div ng-click="toggle()">{{title}}</div>'
            + '<div ng-show="showMe" ng-transclude></div>'
            + '</div>',
            link: function (scope, element, attrs, ctrl) {
                scope.showMe = false;
                ctrl.add(scope);
                scope.toggle = function toggle() {
                    scope.showMe = !scope.showMe;
                    ctrl.got(scope);
                }
            }
        }
    });
    <acc>
        <expander  ng-repeat="x in list" >
            {{x.text}}
        </expander>
    </acc>
原文地址:https://www.cnblogs.com/m110/p/8670516.html