让前端飞

AngularJS Directive 分析+案例

2016-10-16  本文已影响0人  Tony_HQ

AngularJS Directive 实现了 web 组件化开发。

什么叫组件呢,<input>就是一个原生组件,就是这么简单。

生产环境中,常常会有这么一个应用场景,点击文字,出现输入框(进入编辑模式),既点击<span>出现<input>,在点击或者键入Enter,退出编辑模式,<input>变回<span>

那么我们是否可以有一个控件叫做<span-input-change>来实现这个功能呢?

Directive spanInputChange

app.directive('spanInputChange', function() {
        function link(scope, element, attrs) {
        }
        return {
            templateUrl:'span_input_change.html',
            transclude: true,
            scope: {
                val: '=valModel',
                afterBlur:'=jfBlur',
                showInput:'=showInput',
                noEmpty:'=noEmpty',
                wString:'=warningString'
            },
            controller:function($scope,$element,$attrs){
                $scope.blurCallback=function(){
                    if($scope.noEmpty&&($scope.val==null||$scope.val.length<1)){
                        //条件不满足时错误提示。
                        $scope.wString='此项不能为空';
                        return;
                    }
                    $scope.showInput=false;
                     //调用回调,在blur 之后。
                    $scope.afterBlur(function(showInput){
                        $scope.showInput=showInput;
                    });
                }
            },
            link: link
        };
    });

span_input_change.html

<input ng-show="showInput" class='form-control varclass'
 ng-blur='blurCallback()' type='text' ng-model='val'>

<span ng-hide="showInput" style="cursor: pointer"
 ng-bind='val' ng-click="showInput=true"
 uib-popover="点击修改" popover-trigger="mouseenter"> </span>

这样就完成了一个简单的组件封装。

想象一下,当你开发一个社交网站的时候,一旦Timeline总共几种类型,那么对应写几个组件,再配合ng-repeat+你写的一个小判断,可以非常高效的完成类似Android RecyclerView的开发。

组件化开发也大大降低了耦合度。
产品更新,可以按组件(模块)更新。

关于Directive的Api,官网有详述,Google也有很多中文版本,若有问题可以评论。

上一篇 下一篇

猜你喜欢

热点阅读