即使在向ngResource添加依赖项后,也会出现$ resource错误

时间:2016-06-02 02:48:57

标签: angularjs ngresource angularjs-ng-resource

我正在尝试使用来自mongolab的$ resource在角度应用中显示数据。我在模块中添加了对ngResource的依赖。它仍然说未知提供商。这里遗漏的是什么?

  

'$ resource未定义'

注意:当我的工厂名称不正确时,我收到错误:未知提供商:employeesProvider< - employees

代码

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js"></script>

<script type="text/javascript">

 //defining module
 var app = angular.module('myApp', ['ngResource']);

 //defining factory
 app.factory('employees', function () {

    return $resource('https://api.mlab.com/api/1/databases/humanresource/collections/Employees',
                    {apiKey: 'removedmykeyforpostinginSO'}
                  );
 });

 //defining controller
 app.controller('myController', function ($scope, employees) 
 {
    $scope.countries = employees.query();
 });  

</script>
</head>

<body ng-app="myApp">
     <div ng-controller="myController">
    <ul>
        <li ng-repeat = "objCountry in countries" >
            {{objCountry.name}}

        </li>
    </ul>
     </div>
</body>
</html>

来自Mongolab的JSON

[ { "_id" : { "$oid" : "57044f95e4b0427faa38585f"} , "name" : "Lijo" , "age" : "30"} ]

1 个答案:

答案 0 :(得分:0)

AngulaJS Documentation开始,推荐的工厂声明方式是:

angular.module('myModule', [])
.factory('serviceId', ['depService', function(depService) {
  // ...
}])

我通过注入$ resource:

更正了我的工厂代码,如下所示
app.factory('employees', function ($resource) {

    return $resource('https://api.mlab.com/api/1/databases/humanresource/collections/Employees',
                    {apiKey: 'jJbAltZ26vuIrgzUQetXh480JM0q9k6p'}
                  );
 });

参考文献:

  1. $resource
  2. Tidy Up Your Angular Controllers with Factories and Services
  3. Angular: Passing data back to my controller from a factory ajax call
  4. Binding variables from Service/Factory to Controllers
  5. Angular passing data from factory to controller