angularjs防抖

1.新建debounce.js,代码如下

function debounce($timeout, $q) {
     
    return function debounce(func, wait, immediate){
     
        var timeout
        var deferred = $q.defer();
        return function () {
     
            var content = this;
            var args = arguments;
            var later = function () {
     
                timeout = null
                if(!immediate){
     
                    deferred.resolve(func.apply(content, args))
                    deferred = $q.defer();
                }
            }
            var callNow = immediate && !timeout;
            if(timeout){
     
                $timeout.cancel(timeout)
            }
            timeout = $timeout(later, wait)
            if(callNow){
     
                deferred.resolve(func.apply(content, args))
                deferred = $q.defer()
            }
            return deferred.promise
        }
    }
}
export  default  debounce()

2.app.js注入服务如下(import debounce from './static/scripts/factory/debounce.js' 和 .factory('debounce',['$timeout','$q',debounce])

import angular from 'angular'
import 'oclazyload'
import uirouter from 'angular-ui-router'
import uiBootstrap from 'angular-ui-bootstrap'
import debounce from './static/scripts/factory/debounce.js'
import headerDev from './static/scripts/diredctive/headerDev.js'
import slidemenuDev from './static/scripts/diredctive/slidemenuDev.js'
import routing from './router.js' //路由
import indexCtrl from  './static/components/index/indexCtrl.js' //主页
import netWork from  './static/components/index/netWork.js' //网络
import commonService from  './static/service/commonService.js' //网络
window.app = angular.module('myProject',['uirouter','uiBootstrap','oclazyload'])
    .config(routing)
    .run(['$rootScope',function($rootScope){
     
        $rootScope.$on('$stateChangeSuccess',function(event,toState){
     
            $rootScope.$broadcast('to-menu', {
     state: toState.name})
        })
    }])
    .service('commonService',commonService)
    .directive('headerDev',headerDev)
    .directive('slidemenuDev',slidemenuDev)
    .controller('indexCtrl',indexCtrl)
    .controller('netWork',netWork)
    .factory('debounce',['$timeout','$q',debounce])
export default app

3.防抖的controller使用$inject注入依赖

myCtr.$inject = ['$scope','debounce'].

4.直接使用debounce例如

html 内容如下

<input type="text" name="activities" ng-model="inputValue" ng-change="changeValue"></input>

js内容如下:

function myCtr($scope,debounce){
     
    $scope.changeValue = debounce(function(){
     
        this.currentValue = inputValue;
    },500)
}

你可能感兴趣的:(angularjs,js,html)