基本介绍
之前我们介绍了angular内置的几种服务,这里我们介绍如何自己定义自己的服务,主要是通过三个方法:factory、service、value
基本使用
factory:可以返回对象,也可以返回一个函数
<!DOCTYPE html> <html lang="en" ng-app="App"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-controller="DemoController"> <h1>{{now}}</h1> <script src="../libs/angular.min.js"></script> <script> var App = angular.module(‘App‘, []); App.factory(‘showTime‘, [‘$filter‘, function ($filter) { return function () { var now = new Date(); return $filter(‘date‘)(now, ‘yy-MM-dd‘); } }]); App.controller(‘DemoController‘, [‘$scope‘, ‘showTime‘, function ($scope, showTime) { $scope.now = showTime(); }]); </script> </body> </html>
<!DOCTYPE html> <html lang="en" ng-app="App"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-controller="DemoController"> <h1>{{now}}</h1> <script src="../libs/angular.min.js"></script> <script> var App = angular.module(‘App‘, []); App.factory(‘showTime‘, [‘$filter‘, function ($filter) { var now = new Date(); return { now: $filter(‘date‘)(now, ‘yy-MM-dd‘) } }]); App.controller(‘DemoController‘, [‘$scope‘, ‘showTime‘, function ($scope, showTime) { $scope.now = showTime.now; }]); </script> </body> </html>
service:和上面的factory有些区别,service里面可以用this追加属性和方法
<!DOCTYPE html> <html lang="en" ng-app="App"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-controller="DemoController"> <h1>{{now}}</h1> <script src="../libs/angular.min.js"></script> <script> var App = angular.module(‘App‘, []); App.service(‘showTime‘, [‘$filter‘, function ($filter) { var now = new Date(); this.now = $filter(‘date‘)(now, ‘yy-MM-dd‘); }]); App.controller(‘DemoController‘, [‘$scope‘, ‘showTime‘, function ($scope, showTime) { $scope.now = showTime.now; }]); </script> </body> </html>
value:类似于常量,和最开始初始化应用模块的ng-init十分相似,全局都可以访问
<!DOCTYPE html> <html lang="en" ng-app="App"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-controller="DemoController"> <h1>{{text}}</h1> <script src="../libs/angular.min.js"></script> <script> var App = angular.module(‘App‘, []); App.value(‘text‘, ‘Hello World!‘);//定义一个常量,相当于ng-init App.controller(‘DemoController‘, [‘$scope‘, ‘text‘, function ($scope, text) { $scope.text = text; }]); </script> </body> </html>