Angularjs实现具有通用功能的多个指令的最佳实践

时间:2013-09-25 20:34:01

标签: angularjs angularjs-directive

我的页面将有越来越多的具有共同功能的指令列表。实现该功能的最佳方式是保持最佳实践和性能。

例如:

Page将有100个指令,每个指令都有公共事件:

  1. 在鼠标悬停时显示隐藏图层
  2. 隐藏div>查看和显示div>编辑点击。
  3. ......

    模板:

    <div class="panel">
        <div class="view">
            <div class="edit-controls hidden">
                <a href="#" class="edit">Edit</a>
            </div>
            <h3>{{......}}</h3>
            <p>{{.....}}</p>
        </div>
        <div class="edit hidden">
            <form>
                ........
            </form>
        </div>
    </div>
    

    选项1.指令:

    appModule.directive('elemTest', [function() {
        return {
            restrict: 'E',
            templateUrl: '.......',
            replace: true,
            controller: function($scope, $element) {
            },
            link: function(scope, element) {
                element.on('mouseover', function() {
                    element.find(".edit-controls").show();
                });
    
                element.on('mouseout', function() {
                    element.find(".edit-controls").hide();
                });
    
                element.find(".edit").on('click', function(event){
                    event.preventDefault();
                    element.children(".view").hide();
                    element.children(".edit").show();
                });
            }
        }
    }]);
    

    选项2.没有链接功能但使用页面底部的jQuery脚本片段处理鼠标悬停/退出/点击事件的指令:

    $(".panel").live('mouseover',function() { 
        .......
    }) 
    
    $(".panel").live('mouseout',function() { 
        .......
    }) 
    
    ..........
    

    选项3.带控制器和ng-click的指令而不是指令链接功能?

    选项4.?

1 个答案:

答案 0 :(得分:2)

使用Angular 1.2.0

选项4:支持ng-mouseover,ng-mouseout(mouseleave?)和ng-click编辑按钮的指令。

简而言之,让你的指令有一个支持这些功能的模板:

在模板中:

...
<div ng-mouseover="showEditControls = true" ng-mouseleave="showEditControls = false">
 <div ng-show="showEditControls">
  <button ng-click="edit()" />
 </div>
</div>
...

在指令中:

...
controller: function($scope){
 $scope.edit = function()
  // do whatever the editor does
 }

}