angular之modal实现

方法一:bootstrap实现

对于bootstrap的实现,感觉功能比较多,比较复杂,不建议实现。

方法二:自己阉割实现

angular.module('myModal',[]).provider('Modal',function($injector){
    this.$get = function($document.$compile,$http,$templateCache,$rootScope,$controller,$q){
        var Modal = function(){
        _.bindAll(this,'close','dismiss','stop');
        
        this.defer = $q.defer();
        this.result = this.defer.promise;        
        }
        
        Modal.openedItems = 0;
        
        Modal.open = function(options){
            Modal.openedItems++;
            var modal = new Modal();
            
            var templatePromise = $http.get(options.templateUrl,{cache:$templateCache});
            
            var resolvePromise = function(){
                var promiseArr = [];
                
                angular.forEach(options.resolve || {},function(value,key){
                    if(angular.isFunction(value) || angular.isArray(value)){
                        promiseArr.push($q.when($injector.invoke(value)));
                    }
                })
                return promiseArr;
            }
        }
        var promises = $q.all([templatePromise].concat(resolvePromise()));
        
        promises.then(function(tplAndVars){
            var body = $document.find('body').eq(0);
            
            var element = angular.elemet('<div class="cover-wrap"></div>' + tplAndVars[0].data);
            
            var modalScope = (options.scope || $rootScope).$new();
            
            modalScope.$close = modal.close;
            modalScope.$dismiss = modal.dismiss;
            modalScope.$stop = modal.stop;
            
            var ctrlLocals = {};
            var resolveIter = 1;
            
            angular.forEach(options.resolve,function(value,key){
                ctrlLocals[key] = tplAndVars[resolveIter++];
            });
            
            ctrlLocals.$scope = modalScope;
            ctrlLocals.$modal = modal;
            
            $controller(options.controller,ctrlLocals);
            
            var angularElement = $compile(element)(modalScope);
            body.append(angularElement);
            
            
            modal.element = angularElement;
            modal.$scope = modalScope;
        });
        
        return modal;
    }
})


你可能感兴趣的:(modal,angualr)