AngularJS:如何在控制器中注入自定义服务?

时间:2014-10-08 18:08:32

标签: angularjs angularjs-directive

我正在使用AngularJS。我有以下页面:

<div ng-controller="UserController">
<h4>Create an account</h4>
<form class="form-horizontal" role="form">

  <div class="form-group">
    <label for="inputLastName" class="col-sm-2 control-label">Last name</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="inputLastName" placeholder="Enter last name" ng-model="user.lastname">
    </div>
  </div>

    <div class="form-group">
    <label for="inputFirstName" class="col-sm-2 control-label">First name</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="inputFirstName" placeholder="Enter first name" ng-model="user.firstname">
    </div>
  </div>
  <div class="form-group">
    <label for="inputEmail" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="inputEmail" placeholder="Email" ng-model="user.email">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button ng-click="createUser()" class="btn btn-primary">Create account</button>
    </div>
  </div>
</form>
</div>

我有UserController:

app.controller('UserController', function ($rootScope, $scope, $location, UserSevice) {

    $scope.users = ContactService.list();

    $scope.createUser = function () {
        UserService.saveUser($scope.user);
        $scope.user = {};
    }

    $scope.deleteUser = function (id) {
        UserService.deleteUser(id);
        if ($scope.user.id == id) $scope.user= {};
    }

    $scope.editUser = function (id) {
        $scope.user= angular.copy(UserService.get(id));
    }
 });

这是UserService:

app.service('UserServices', function ($http, $location) { 
   // some logic
}

但我认为我必须提供服务提供商,但我不知道该怎么做

Error: [$injector:unpr] Unknown provider: UserSeviceProvider <- UserSevice
http://errors.angularjs.org/1.2.25/$injector/unpr?p0=UserSeviceProvider%20%3C-%20UserSevice
    at http://localhost:8080/app-web/js/lib/angular.js:78:12
    at http://localhost:8080/app-web/js/lib/angular.js:3802:19
    at Object.getService [as get] (http://localhost:8080/app-web/js/lib/angular.js:3930:39)
    at http://localhost:8080/app-web/js/lib/angular.js:3807:45
    at getService (http://localhost:8080/app-web/js/lib/angular.js:3930:39)
    at invoke (http://localhost:8080/app-web/js/lib/angular.js:3957:13)
    at Object.instantiate (http://localhost:8080/app-web/js/lib/angular.js:3977:23)
    at http://localhost:8080/app-web/js/lib/angular.js:7281:28
    at http://localhost:8080/app-web/js/lib/angular.js:6670:34
    at forEach (http://localhost:8080/app-web/js/lib/angular.js:332:20) <div ng-view="" class="ng-scope"> 

1 个答案:

答案 0 :(得分:1)

你有一个错字:

app.service('UserServices', function ($http, $location) { 

但是你注入了UserServiceUserSevice实际上 - 我猜错了一些错别字)