This is my demo using angularjs, for creating a service file, and adding service to a controller.
I have two problems with my demo:
<script src="HomeController.js"> before <script src="MyService.js"> I get this error,Error: [ng:areq] Argument 'HomeController' is not a function, got undefined
<script src="MyService.js"> before <script src="HomeController.js"> I get the following error,Error: [$injector:unpr] Unknown provider: MyServiceProvider <- MyService
My source:
File Index.html:
<!DOCTYPE html> <html >     <head lang="en">…</head>     <body ng-app="myApp">         …         <div ng-controller="HomeController">             <div ng-repeat="item in hello">{{item.id + item.name}}</div>         </div>          <script src="Scripts/angular.js"></script>         <script src="Scripts/angular-route.js"></script>          <!-- App libs -->         <script src="app/app.js"></script>             <script src="app/services/MyService.js"></script>         <script src="app/controllers/HomeController.js"></script>     </body> </html>   File HomeController.js:
(function(angular){     'use strict';      var myApp = angular.module('myApp',[]);      myApp.controller('HomeController',function($scope,MyService){             $scope.hello=[];         $scope.hello = MyService.getHello();     }); })(window.angular);   File MyService.js:
(function(angular){     'use strict';      var myApp = angular.module('myApp',[]);      myApp.service('MyService', function () {         var hello =[  {id:1,name:'cuong'},             {id:2,name:'nguyen'}];         this.getHello = function(){             return hello;         };     });  })(window.angular); 
                This creates a new module/app:
var myApp = angular.module('myApp',[]);   While this accesses an already created module (notice the omission of the second argument):
var myApp = angular.module('myApp');   Since you use the first approach on both scripts you are basically overriding the module you previously created.
On the second script being loaded, use var myApp = angular.module('myApp');.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With