I just started learning AngularJS and I am at a point of creating controllers and services ( factory ).
My folder structure is like the following:
Scripts
|
|-- Controllers
|
|-- invoiceController.js
|-- customerController.js
|
|-- Services
|
|-- invoiceServices.js
|-- customerServices.js
|
|-- app.js
Now I want to separate all the logics based on object ( eg Invoices, Customers, ... ).
So that I have a controller and service for my invoices, and one of both for my customers and so on.
But how do I inject the correct service in my controller?
When I try this:
app.js
(function () {
'use strict';
angular.module('skycountApp', [
invoiceService
]);
})();
invoiceController.js
(function () {
'use strict';
angular
.module('skycountApp')
.controller('InvoiceController', invoiceController);
invoiceController.$inject = ['$scope', 'Invoices'];
function homeController($scope, Invoices) {
$scope.text = Invoices;
}
})();
invoiceService.js
(function () {
'use strict';
var invoiceService = angular.module('invoiceService', ['ngResource']);
invoiceService.factory('Invoices', ['$resource',
function ($resource) {
return 'All invoices';
}
]);
})();
index.html
<!DOCTYPE html>
<html ng-app="skycountApp">
<head>
<meta charset="utf-8" />
<title>DOTA 2 Heroes</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-resource.js"></script>
<script src="app.js"></script>
</head>
<body ng-cloak>
<div ng-controller="InvoiceController">
<h1>{{text}}</h1>
</div>
</body>
</html>
I see the message All invoices.
But now I have injected the service in the app when it gets created. I will have more services ( one for customers, one for payments, ... ) so injecting them all in the beginning sounds silly to me.
How can I inject the correct service in the correct controller?
app.js
(function () {
'use strict';
angular.module('skycountApp', [
//invoiceService this is not needed here
]);
})();
invoiceController.js
(function () {
'use strict';
// Its only needed here, how to inject it??????
angular
.module('skycountApp')
.controller('InvoiceController', invoiceController);
invoiceController.$inject = ['$scope', 'Invoices'];
function homeController($scope, Invoices) {
$scope.text = Invoices;
}
})();
first of all why you are creating services on the the different angularjs module
(function () {
'use strict';
var invoiceService = angular.module('invoiceService', ['ngResource']);
invoiceService.factory('Invoices', ['$resource',
function ($resource) {
return 'All invoices';
}
]);
})();
simply create service on same angularjs module
(function () {
'use strict';
angular.module('skycountApp').factory('Invoices',['$resource',
function ($resource) {
return 'All invoices';
}
]);
})();
and then in your controller
(function () {
'use strict';
angular.module('skycountApp').controller('InvoiceController', function(Invoices){
$scope.text = Invoices;
})();
Note : include ngResource in app.js angular.module
Update : for using service define in other module you need to inject the module
(function () {
'use strict';
angular.module('skycountApp',['invoiceService']).controller('InvoiceController', function(Invoices){
$scope.text = Invoices;
})();
InvoiceController is a part of skycountApp module. It is coupled with it, and putting invoiceService into separate module doesn't make much sense. Doing
angular.module('skycountApp', ['invoiceService']);
means only that invoiceService was listed as a dependency for the module, and now the module has access to its components. Invoices service isn't injected and doesn't cause any overhead when InvoiceController isn't used.
If invoice and customer components will rarely be used by the same user, you can make invoiceService and InvoiceController a part of invoice module and use it only where it is needed (consider this module a separate app). But in the end you will most likely find that all js files have to be built into single bundle for the sake of performance.
Related
How to Define a new function in angular can anybody please help me out
My code is like this:
var app = angular.module('rtsApp', ['ngMaterial', 'ngMessages', 'ngStorage','ngRoute', 'restangular','timepickerPop', 'ngStomp', 'ngCookies', 'angular-cron-gen','uiSwitch','ngMaterial', 'md.data.table']);
app.config(function(RestangularProvider) {
newFunction(RestangularProvider);//I need newFunction here
RestangularProvider.setDefaultHeaders({
"X-API-KEY": "sks#2017",
"Content-Type": "application/json"
});
Actually I am Getting This Error
Failed to instantiate module rtsApp due to:
ReferenceError: newFunction is not defined
at http://localhost:3000/dist/js/scripts.min.js:1738:5
at Object.invoke (http://localhost:3000/dist/js/vendor.min.js:82:460)
at d (http://localhost:3000/dist/js/vendor.min.js:80:333)
at http://localhost:3000/dist/js/vendor.min.js:80:472
at q (http://localhost:3000/dist/js/vendor.min.js:46:7)
at g (http://localhost:3000/dist/js/vendor.min.js:80:234)
at gb (http://localhost:3000/dist/js/vendor.min.js:84:352)
at c (http://localhost:3000/dist/js/vendor.min.js:60:57)
at Wc (http://localhost:3000/dist/js/vendor.min.js:60:370)
at ye (http://localhost:3000/dist/js/vendor.min.js:59:45)
try it :-
another scenario is follow below code,
'use strict';
var deck = angular.module('app',
['ui.router',other lib...]);
angular.module("app").config(["$breadcrumbProvider", "$httpProvider", function ($breadcrumbProvider, $httpProvider) {
$breadcrumbProvider.setOptions({
prefixStateName: 'userHome.main',
template: 'bootstrap3'
});
//Do No Remove This Line
$httpProvider.defaults.withCredentials = true;
}]);
Create a file and define a module in the file. For example create globalFunctions.js and add this file to your index.html file with this :
<script src="/path/to/file/location/globalFunctions.js"></script>
Define a module and also your global functions. like this:
(function () {
angular.module('test', []);
})();
function test() {
console.log("test");
}
Inject it in main app (app.module.js) and call it:
(function() {
'use strict';
var app = angular.module('app', [
'test',
...
]);
app.config(function($routeProvider, $locationProvider) {
test();
});
})();
Update
All files for a simple test:
app.module.js
(function () {
var app = angular.module('app', [
'ngRoute',
'global'
]);
app.config(function ($routeProvider, $locationProvider) {
test();
});
})();
test.module.js
(function () {
angular.module('global', []);
})();
function test() {
console.log("it is test function here");
}
index.html
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.16/angular-route.min.js"></script>
<script src="app.module.js"></script>
<script src="test.module.js"></script>
<body ng-app="app">
<h2>It is a test</h2>
</body>
</html>
This Plunker provided for my solution
I have an angularjs project with 6 services. Everyone of them works fine, but now if i create a new service and try to inject it, it fails. I tried to inject the same service in another project and it works.
Here is the service:
app-services/test.service.js
(function () {
'use strict';
angular
.module('app')
.factory('TestService', TestService);
TestService.$inject = ['$scope'];
function TestService($scope) {
var service = {};
service.Test = Test;
return service;
function Test() {
//Stuff
}
}
})();
Here is the controller in which i try to inject it: app-index/functions/functions.controller.js
(function () {
'use strict';
angular
.module('app')
.controller('FunctionController', FunctionController);
FunctionController.$inject = ['$scope', 'FlashService', '$location', 'UploaderService', '$q','TestService'];
function FunctionController($scope, FlashService, $location, UploaderService, $q, TestService) {
var vm = this;
var fileContainers;
$scope.UploadFile = UploadFile;
function UploadFile() {
TestService.Test();
}
}
})();
In the index.html
<script src="app.js"></script>
<script src="app-services/test.service.js"></script>
<script src="app-index/functions/functions.controller.js"></script>
Error
HTML1300: NavegaciĆ³n realizada.
localhost:44373
Error: [$injector:unpr] http://errors.angularjs.org/1.6.0/$injector/unpr?
p0=TestServiceProvider%20%3C-%20TestService%20%3C-%20FunctionController
at Anonymous function
(https://code.angularjs.org/1.6.0/angular.min.js:44:389)
at d (https://code.angularjs.org/1.6.0/angular.min.js:42:60)
at Anonymous function
(https://code.angularjs.org/1.6.0/angular.min.js:44:449)
at d (https://code.angularjs.org/1.6.0/angular.min.js:42:60)
at e (https://code.angularjs.org/1.6.0/angular.min.js:42:298)
at instantiate (https://code.angularjs.org/1.6.0/angular.min.js:43:242)
at Anonymous function
(https://code.angularjs.org/1.6.0/angular.min.js:93:137)
at link (https://code.angularjs.org/1.6.0/angular-route.min.js:7:316)
at Anonymous function
(https://code.angularjs.org/1.6.0/angular.min.js:16:45)
at ta (https://code.angularjs.org/1.6.0/angular.min.js:84:35) <div
class="ng-scope" style="width: 100%; height: 100%;" ng-view="">
As i said, the other services injected in the controller are working. And I don't think the problem is in TestService since it is working on another project.
I'm developing in Visual Studio
Edit: I removed $scope from service, but it still doesn't work
Edit 2: It looks like the problem is the caching. It loads the old version of index.html that hasn't got the reference of the new service..
I'm trying to do a simple $anchorScroll but my controller is not working.
here's my module
(function () {
'use strict';
angular.module('app', [
'ui.bootstrap',
'app.article'
]);
})();
and here's my controller
(function () {
'use strict';
angular
.module('app.article')
.controller('Article', Article);
function Article($scope, $location, $anchorScroll) {
var vm = this;
vm.backToTop = backToTop;
function backToTop() {
$location.hash('top');
$anchorScroll();
}
}
})();
I'm adding the ng-app and the ng-controller correctly.
Any ideas?
here's the plunkr: https://plnkr.co/edit/Rnsahf24ds1pYWKz9Ete?p=preview
There are few things that you are missing in your code,
(i) You are refering to angular2 script while your code is defined for angular 1.3, so change the reference as
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>
(ii) You need to refer to bootstrap library and necessary css if you are injecting in angular application
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.2.js"></script>
Here is the working App
I am trying to make a login page. I have one controller on my login page. On button click I am showing an alert. But it is not displaying. I created a module of controller that why I am not able to create plunker or fiddle. I will share my small code in which I write a controller.
Here is my code
LoginCtrl.js
define(function () {
'use strict';
function ctrl($scope, $state) {
$scope.login = function () {
alert("--")
};
}
ctrl.$inject = ['$scope', '$state'];
return ctrl;
});
controller.js
/*global define, require */
define(function (require) {
'use strict';
var controllers = angular.module('app.controllers', []);
controllers.controller('LoginCtrl', require('controllers/LoginCtrl'));
return controllers;
});
Make sure in your HTML file you have added the controller name to the parent element or the appropriate element.You need to give the same controller name in both your HTML file and also the js file.
Make sure your controller file is included in your index.html file.
I'm getting the below error while loading my web pages:
Argument 'channelsAppController' is not a function, got undefined
I have 2 different web pages and one Layout page which includes 2 different java-script files:
<script src ="/Scripts/Views2/Channel.js"></script>
<script src ="/Scripts/Views2/Channel_Create.js"></script>
Here is the begging of each scripts:
Channel.js
(function() {
var myApp;
myApp = window.angular.module("myApp", []);
myApp.controller("channelsAppController", function($scope, $http, $compile) {
Channel_create.js
(function() {
var myApp;
myApp = window.angular.module("myApp", []);
myApp.controller("channelCreateController", function($scope, $http, $compile) {
$scope.Channel = {
When I load either of the pages I get the error mentioned earlier.
If I comment out one of the scripts in the layout the page...the page that doesn't uses the script loads and doesn't generate an error.
Each page has their respective controller specified in the root div.
I'm trying to figure out whats causing the errors:
How can I include multiple javascript files in a layout page while using angular ?
Channel.js
(function() {
var myApp;
myApp = window.angular.module("myApp", []); //Module definition
myApp.controller("channelsAppController", function($scope, $http, $compile) {
Channel_create.js
(function() {
var myApp;
myApp = window.angular.module("myApp"); //Module retrieval.
myApp.controller("channelCreateController", function($scope, $http, $compile) {
$scope.Channel = {