服务的好处暂且不讨论,先写,
1.定义模块
2.利用工厂方法写服务
3.注入到controller
1.
1 <!doctype html> 2 <html ng-app="myApp"> 3 <head> 4 <script src="angular.js"></script> 5 <style type="text/css"> 6 .btn{ 7 width: 60px; 8 height: 30px; 9 line-height: 30px; 10 text-align: center; 11 border-radius: 10px; 12 border: solid 1px blue; 13 } 14 .error{ 15 border:solid 1px red; 16 } 17 .warning{ 18 color: yellow; 19 } 20 </style> 21 </head> 22 <body ng-controller="myController"> 23 24 <ul> 25 <li ng-repeat="item in items"> 26 {{item.name}} 27 </li> 28 </ul> 29 <script type="text/javascript"> 30 var myApp = angular.module(‘myApp‘,[]);//定义模块 31 myApp.factory(‘Items‘,function () {//定义服务Items 32 var items = {}; 33 items.query = function () { 34 return [ 35 { 36 name:111 37 }, 38 { 39 name:222 40 } 41 ]; 42 } 43 return items; 44 }); 45 function myController ($scope,Items) {//定义controller 并且依赖注入Items (Items其实就是一个对象)服务 46 $scope.items = Items.query();//调用服务返回给我们所需要的数据 47 } 48 </script> 49 </body> 50 </html>
angular入门-如何写一个服务
时间: 2024-10-05 11:16:43