Page 136 - AngularJS权威教程
P. 136

116  第 14 章  服务


                         }
                     };
                 });

                 githubService中只包含了一个方法,可以在应用的模块中调用。

             14.2 使用服务


                 可以在控制器、指令、过滤器或另外一个服务中通过依赖声明的方式来使用服务。AngularJS
             会像平时一样在运行期自动处理实例化和依赖加载的相关事宜。

                 将服务的名字当作参数传递给控制器函数,可以将服务注入到控制器中。当服务成为了某个
             控制器的依赖,就可以在控制器中调用任何定义在这个服务对象上的方法。

                 angular.module('myApp', ['myApp.services'])
                 .controller('ServiceController', function($scope, githubService) {
                     // 我们可以调用对象的事件函数
                     $scope.events = githubService.events('auser');
                 });
                 githubService服务已经被注入到ServiceController中,可以像使用任何其他服务一样使
             用它。

                 修改一下例子,用视图中输入的GitHub用户名为参数来访问GitHub API。同第2章介绍的内
             容一样,将username属性和视图进行绑定。
                 <div ng-controller="ServiceController">
                     <label for="username">
                         Type in a GitHub username
                     </label>
                     <input type="text"
                         ng-model="username"
                         placeholder="Enter a GitHub username" />
                     <ul>
                         <li ng-repeat="event in events">
                         <!--
                             event.actor and event.repo are returned
                             by the github API. To view the raw
                             API, uncomment the next line:
                         -->
                         <!-- {{ event | json }} -->
                           {{ event.actor.login }} {{ event.repo.name }}
                         </li>
                     </ul>
                 </div>
                 基于双向数据绑定,我们现在可以通过监视$scope.username来响应视图中的数据变化。

                 .controller('ServiceController',
                     function($scope, githubService) {
                     // 注意username属性的变化
                     // 如果有变化就运行该函数
                     $scope.$watch('username', function(newUsername) {
                         // 从使用JSONP调用Github API的$http服务中返回promise
                         githubService.events(newUsername)
                             .success(function(data, status, headers) {
                                 // success函数在数据中封装响应
   131   132   133   134   135   136   137   138   139   140   141