AngularJS(5)导航焦点自动切换

Angular写一个指令,点击时候,自动切换焦点。

创建指令

  • 创建指令命令
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    angular.module('模块名称',[])
    .directive('指令名称-驼峰命名',['参数',function(参数){
    var path = $location.path();
    return{
    restrict:'A',//类型
    link:function($scope,iElm,iAttrs,controller){
    //操作
    }
    };
    }]);

指令调用

如果名称为 homeIndex 使用的时候为 home-index

源码

  • 创建指令directive

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    (function(angular){
    angular.module('moviecat.directives.autofocus',[])
    .directive('autoFocus',['$location',function($location){
    var path = $location.path();
    return{
    restrict:'A',
    link:function($scope,iElm,iAttrs,controller){
    var aLink = iElm.children().attr('href');
    var type = aLink.replace(/#(\/.+?)\/\d+/,'$1');
    if(path.startsWith(type)){
    iElm.parent().children().removeClass('active');
    iElm.addClass('active');
    }
    iElm.on('click',function(){
    iElm.parent().children().removeClass('active');
    iElm.addClass('active');
    });
    }
    };
    }]);
    })(angular);
  • 使用

    1
    2
    3
    4
    5
    6
    7
    ...
    <ul class="nav nav-sidebar">
    <li auto-focus class="active"><a href="#/in_theaters/1">正在热映</a></li>
    <li auto-focus><a href="#/coming_soon/1">即将上映</a></li>
    <li auto-focus><a href="#/top250/1">TOP250</a></li>
    </ul>
    ...