AngularJS 部分通用Directive/Factory/Filter分享

这些Directive/Factory/Filter是在我负责前端的Reader项目中所使用到的, 由于我已经从项目组退出, 本着现成的代码不用就是浪费的理念, 我决定把这些通用性较强的代码发出来, 也顺便来纪念我开发Reader项目的日子.或者混出一篇博文什么的.

Directive

粘贴前事件:

App.directive 'beforePaste',($timeout, $parse)->  
    (scope, element, attrs)->
        fn = $parse attrs['beforePaste']
        element.on 'paste', (event)->
            scope.$apply ->
                fn scope, $event:event

可编辑元素:

App.directive 'contenteditable',->  
    restrict: 'A'
    require: '?ngModel'
    link: (scope, element, attrs, ngModel)->
        if ngModel
            ngModel.$render = (value)->
                element.html ngModel.$viewValue or ''

            read = ->
                html = element.html()
                if attrs.stripBr and html is '<br>'
                    html = ''
                ngModel.$setViewValue html

            element.on 'blur keyup change',->
                scope.$apply read

            read()

可编辑元素输入事件:

App.directive 'contenteditableInput',($timeout,$parse)->  
    (scope, element, attrs)->
        fn = $parse attrs['contenteditableInput']
        element.on 'blur keyup change paste', ->
            $timeout ->
                scope.$apply ->
                    fn scope, $event:event

页面滚动事件:

App.directive 'whenScrolled', ($parse, $window)->  
    (scope, element, attrs)->
        $window = angular.element $window
        $window.on 'scroll',(event)->
            elementHeight = element.height()
            scrollAmount = $window.scrollTop()
            delta = 1000
            if elementHeight - (scrollAmount + delta) < 0
                scope.$apply attrs.whenScrolled

Factory

通用数据存储:

App.factory 'Data',->  
    data = {}
    'set':(key, value)->
        data[key] = value
    'get':(key)->
        data[key]
    'rm':(key)->
        delete data[key]

Filter

判断存在:

App.filter 'isExist',->  
    (input)->
        input?