2014
Jul
30

Angularjs Service

在 Angularjs 里, Service 就像是一个 Object ,这个 Object 把相关功能包装起来,当你需要使用某些功能时,就能直接呼叫他,例如我们常常会用到 AJAX , 你可以使用 $http 这个 Angularjs 内建的 service ,来发出 AJAX Request 。

如何写一个 Angularjs Service

写一个 Service 非常的简单,这里我先建立一个新的 module 叫 myService ,然后我定义一个新的 service 叫做 serviceSample,再来写一个 Method run ,这个 function 会回传一行文字,看看下面的范例,只要简单的五行程式码,就能够建立一个客制化的 service。

Example
  1. var m = angular.module("myService", []);
  2. m.service('serviceSample', function () {
  3. this.run = function () {
  4. return "Hello World! <br />This text is rendered by angularjs service.";
  5. };
  6. });

如何使用客制化的 Angularjs Service

首先我们要先载入刚刚写好的 Angularjs Module 「myService」,只要在宣告 主 Module 时的第二个参数,填上我要载入的 Module 名称即可,接著在 controller function 中的参数写上要使用的 service 名称,这个范例中我写了三个 services ,其中 $scope 与 $sce 是 Angularjs 内建的, serviceSample 则是我刚刚载入的 service ,只要载入成功,我们就能直接使用刚刚定义好的 Method。

Example
  1. var myapp = angular.module("myapp", ['myService']);
  2. myapp.controller('ct', function ($scope, $sce, serviceSample) {
  3. $scope.text = $sce.trustAsHtml(serviceSample.run());
  4. });

全部的程式码

Example
  1. <!doctype html>
  2. <html >
  3. <head>
  4. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
  5. <script>
  6.  
  7. var m = angular.module("myService", []);
  8. m.service('serviceSample', function () {
  9. this.run = function () {
  10. return "Hello World! <br />This text is rendered by angularjs service.";
  11. };
  12. });
  13.  
  14. var myapp = angular.module("myapp", ['myService']);
  15. myapp.controller('ct', function ($scope, $sce, serviceSample) {
  16. $scope.text = $sce.trustAsHtml(serviceSample.run());
  17. });
  18.  
  19.  
  20.  
  21. </script>
  22.  
  23. </head>
  24. <body ng-app="myapp">
  25.  
  26. <div class="sample-wrap" ng-controller="ct">
  27. <h2 ng-bind-html="text"></h2>
  28. </div>
  29.  
  30.  
  31.  
  32. </body>
  33. </html>


回應 (Leave a comment)