学习angular的插件写法和制作;
<!DOCTYPE html> <html ng-app="APP"> <head> <meta charset="UTF-8"> <title>angular-refresh example</title> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.12/angular.min.js"></script> </head> <body ng-controller="ExampleController"> <angular-refresh url="http://filltext.com/?rows=10&fname={firstName}&lname={lastName}&callback=JSON_CALLBACK" ng-model="people" interval="5000" method="jsonp"> </angular-refresh> <ul ng-repeat="person in people"> <li>{{person.fname}} {{person.lname}}</li> </ul> <!-- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script> --> <script> //直接依赖这个datarefresh模块; angular.module("APP",["datarefresh"]). controller("ExampleController",['$scope',function($scope){ }]); </script> <script> angular.module('datarefresh', []) .directive('angularRefresh', ['$parse', '$timeout', '$http', function ($parse, $timeout, $http) { return { //E为tag类型, A为属性, C应该是注释; restrict: 'E', //template的元素肯定要一个总元素; template: '<div></div>', /* 这个元素相当于是配置..一点用处都没有; */ replace: true, link: function (scope, element, attrs) { console.log(element); var isRunning = true; var method = 'get'; var url = ''; function successFunction(data) { if (data !== undefined && isRunning) { try { /* $parse(attrs.ngModel).assign返回的是一个闭包; 这个语句相当于执行 : 1 : scope.people = data; 2 : scope.$apply() */ $parse(attrs.ngModel).assign(scope, data); } catch (error) { //Just in case scope got detroyed while we were trying to update console.log(error); } } if (isRunning) { $timeout(function () { refreshFromUrl(url, interval); }, interval); } } function refreshFromUrl(url, interval) { if (isNaN(interval)) { interval = 2000; }; //通过$http的方式获取JSONP的数据; $http[method](url).success(function (data, status, headers, config) { //对数据整理; successFunction(data); }) .error(function (data, status, headers, config) { console.log(data); }); } //通过各种方式获取配置验证是否为空; if (attrs.ngModel !== undefined && attrs.ngModel !== '' && attrs.url !== undefined && attrs.url !== '') { //获取间隔刷新的时间; var interval = parseInt(attrs.interval); if(isNaN(interval)) interval = 2000; //获取请求方式; if(attrs.method !== undefined && attrs.method !== '') { if(attrs.method.toLowerCase() == 'get' || attrs.method.toLowerCase()=='jsonp') { method = attrs.method.toLowerCase(); } } //配置url; url = attrs.url; refreshFromUrl(url, interval); } scope.$on('$destroy', function () { isRunning = false; }); } } }]); </script> </body> </html>