简体   繁体   中英

Angular JS Injecting Custom Service

I can't get angular to accept my custom service, which is in a seperate file. I know this is all over stack overflow, but I just can't tell where I'm messing up.

Html:

<!DOCTYPE html>
<html lang="en" ng-app="angularApp">
<head>
  <!-- ANGULAR -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-sanitize.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-route.js"></script>
  <link href="styles/angularApp.css" rel="stylesheet">
  <script src="scripts/controllers/angularApp.js"></script>
  <script src ="scripts/services/clearCodemirror.js"></script>

Main angular javascript file (contains my controller)

var myApp = angular.module("angularApp", ["ui.codemirror","ui.bootstrap", "ngSanitize", "ngRoute"]);

myApp.controller("mainController", ["$scope", "$timeout", "clearCodemirror", function($scope, $timeout, clearCodemirror){

Service I'm trying to inject:

var myApp = angular.module("angularApp");

myApp.service("clearCodemirror", function(cm){

Error I keep getting:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.6/$injector/modulerr?p0=angularApp&p1=Error…oogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.6%2Fangular.min.js%3A29%3A56)

I only included the beginnings of each file so you guys wouldn't have to wade through tons of code. Where am I screwing up?

Thanks!

By calling angular.module("angularApp") from your 2nd file, you are recreating a angular module, and NOT getting a reference to the module that was created on the previous file.

There are a few ways to solve that. The simplest one (on my point of view) is to set your angular app to a window.VARIABLE.

window.myApp = angular.module("angularApp", ["ui.codemirror","ui.bootstrap", "ngSanitize", "ngRoute"]);

Then, from your 2nd file you can:

var myApp = window.myApp;

myApp.service("clearCodemirror", function(cm){

There are better ways to do that. However, this one you get you going. Cheers!

Hi you are not re creating the module you are getting the existing module by var myApp = angular.module("angularApp"); as the docs states :- https://docs.angularjs.org/api/ng/function/angular.module

When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved.

i tried with 1.3.14 , i didnt got any error, which version are you using:-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM