将组件封装起来在项目中开发很实用,之前遭遇过一次痛苦的经历,那阵子改的要吐血了。常用的组件封装起来,改公共的地方,往往多处受用。
例如:我在项目中引用 tips.text('加载中。。。',false) ;
参数设为false时,tips会一直显示,可以在请求成功后,让tips 隐藏了;参数不设置的时候,tips两秒后消失。
PS:isHide && (timeoutId = setTimeout(function() {ele.style.display = 'none'; }, 2000)); 这句困扰了好久,这是tips一直显示的原因,最后终于明白了,&&方法:当只有前面的为true,后面的才可以执行,并返回后面的值。附上篇觉得写得不错的一篇文章:
http://wenrunchang123.iteye.com/blog/1749802
module.exports = function() { angular.module('App').factory('tips', function() { var $ = angular.element; var ele = angular.element('<div id="tips"></div>')[0]; var $ele = $(ele); var style = { display: 'none', padding: '5px 10px', 'text-align': 'center', position: 'fixed', left: '50%', transform: 'translate(-50%, -50%)', 'background-color': 'rgba(0,0,0,.6)', color: '#fff', 'z-index': '9999', 'border-radius': '5px' }; angular.element(ele).css(style); document.body.appendChild(ele); var timeoutId = null; return { text: function(msg, isHide) { isHide = isHide !== undefined ? isHide : true; ele.style.display = 'inline-block'; ele.style.bottom = '50%'; ele.innerHTML = msg; clearTimeout(timeoutId); isHide && (timeoutId = setTimeout(function() { ele.style.display = 'none'; }, 2000)); }, hide: function() { ele.style.display = 'none'; }, tips: function(options) { if (options.style) { for (var p in options.style) { ele.style[p] = options.style[p]; } } ele.style.display = 'inline-block'; ele.innerHTML = options.msg; clearTimeout(timeoutId); (options.isHide || options.isHide === undefined) && (timeoutId = setTimeout(function() { ele.style.display = 'none'; }, options.timeout || 2000)); } } }); };