I would like to call my service from within app.config.
When searching for this, I found this question with a solution that i tried to follow (not the accepted answer, but the solution below with the title "Set up your service as a custom AngularJS Provider")
However with that solution and with the suggested alternative as well i run into problems when i am trying to call the service from within my app.config (The service does not seem to be called at all). I am new to angular and javascript and don't really know how to debug this properly (i am using firebug). I hope you can help me with some pointers and possibly a solution.
Current Code (trying to implement the "possible alternative" from the linked question:
angular.module('myApp', [
'ngRoute',
])
.config(['$routeProvider', '$locationProvider', '$provide', function($routeProvider, $locationProvider, $provide) {
$provide.service('RoutingService',function($routeParams){
var name = $routeParams.name;
if (name == '') {name = 'testfile'}
var routeDef = {};
routeDef.templateUrl = 'pages/' + name + '/' + name + '.html';
routeDef.controller = name + 'Ctrl';
return routeDef;
})
//Here i would like to get a hold of the returned routeDef object defined above.
$routeProvider.when('/name:', {
templateUrl: RoutingService.templateUrl,
controller: RoutingService.controller
});
My previous attempt was to declare the Service like this via a provider:
var ServiceModule = angular.module('RoutingServiceModule', []);
ServiceModule.provider('routingService', function routingServiceProvider(){
this.$get = [function RoutingServiceFactory(){
return new RoutingService();
}]
});
function RoutingService(){
this.getUrlAndControllerFromRouteParams = function($routeParams){
var name = $routeParams.name;
var routeDef = {};
routeDef.templateUrl = 'pages/' + name + '/' + name + '.html';
routeDef.controller = name + 'Ctrl';
return routeDef;
}
}
and tried to call it like i would usually call a service in a controller (after adding the RoutingServiceModel to the dependencies of myAppof course). In both cases the templateUrl and controller are not set when i navigate to my views, so I guess i am missing some dependencies, or am not calling the service correctly.
Any ideas?
during the config phase, only providers can be injected (with the
exception of the services in the AUTO module--$provide and $injector).
Please check this working demo: http://jsfiddle.net/nxbL66p2/
angular.module('Joy',[])
.config(function($provide) {
$provide.provider('greeting', function() {
this.$get = function() {
return function(name) {
alert("Hello, " + name);
};
};
});
})
.controller('MyCtrl', ['$scope', 'greeting', function ($scope, greeting) {
$scope.greet = function () {
greeting('Joy');
};
}]);
Simple HTML:
<div ng-app="Joy">
<div ng-controller="MyCtrl">
<div ng-click="greet()">Click to greet.</div>
</div>
</div>
Reference: https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection
Angular's terminology is a bit of a mess, because 'service' and 'provider' may designate different things, depending on the context. According to the statement in the manual,
An Angular service is a singleton object created by a service factory.
These service factories are functions which, in turn, are created by a
service provider. The service providers are constructor functions.
When instantiated they must contain a property called $get, which
holds the service factory function.
You can't inject services in config (except constant), only service providers, and your RoutingService is inapplicable there.
Technically, you can get a service there with
RoutingServiceProvider.$get();
But it will make a separate instance (rather than singleton object), and the usage of $routeParams makes no sense at the moment when it is being called in config.
You can have templateUrl as function (see the manual), while dynamic controller names aren't suitable for route configuration, define them within templates with ng-controller instead.
Related
I'm using ruby on rails with angularjs one, and testing it with teaspoon-jasmine for the first time and am running into issues. Basically, I have a controller that creates an empty array and upon load calls a factory method to populate that array. The Factory makes an http request and returns the data. Right now, i'm trying to test the controller, and i'm trying to test that 1) the factory method is called upon loading the controller, and 2) that the controller correctly assigns the returned data through it's callback. For a while I was having trouble getting a mocked factory to pass a test, but once I did, I realized I wasn't actually testing my controller anymore, but the code below passes. Any tips on how I can still get it to pass with mock, promises/callbacks, but accurately test my controller functionality. Or should I even test the this at all in my controller since it calls a factory method and just gives it a callback? My 3 files are below. Can anyone help here? It would be greatly appreciated
mainController.js
'use strict';
myApp.controller('mainController', [ 'mainFactory', '$scope', '$resource', function(factory, scope, resource){
//hits the /games server route upon page load via the factory to grab the list of video games
scope.games = [];
factory.populateTable(function(data){
scope.games = data;
});
}]);
mainFactory.js
'use strict';
myApp.factory('mainFactory', ['$http', '$routeParams', '$location', function(http, routeParams, location) {
var factory = {};
factory.populateTable = function(callback) {
http.get('/games')
.then(function(response){
callback(response.data);
})
};
return factory;
}]);
And finally my mainController_spec.js file
'use strict';
describe("mainController", function() {
var scope,
ctrl,
deferred,
mainFactoryMock;
var gamesArray = [
{name: 'Mario World', manufacturer: 'Nintendo'},
{name: 'Sonic', manufacturer: 'Sega'}
];
var ngInject = angular.mock.inject;
var ngModule = angular.mock.module;
var setupController = function() {
ngInject( function($rootScope, $controller, $q) {
deferred = $q.defer();
deferred.resolve(gamesArray);
mainFactoryMock = {
populateTable: function() {}
};
spyOn(mainFactoryMock, 'populateTable').and.returnValue(deferred.promise);
scope = $rootScope.$new();
ctrl = $controller('mainController', {
mainFactory: mainFactoryMock,
$scope: scope
});
})
}
beforeEach(ngModule("angularApp"));
beforeEach(function(){
setupController();
});
it('should start with an empty games array and populate the array upon load via a factory method', function(){
expect(scope.games).toEqual([])
mainFactoryMock.populateTable();
expect(mainFactoryMock.populateTable).toHaveBeenCalled();
mainFactoryMock.populateTable().then(function(d) {
scope.games = d;
});
scope.$apply(); // resolve promise
expect(scope.games).toEqual(gamesArray)
})
});
Your code looks "non-standard" e.g still using scope.
If you are just starting with angular I hardly recommend you to read and follow this:
https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
Angular controllers cannot be tested, extract the logic into factories/services and test from there.
my question is if i can share scopes, for example
i have one function
$scope.init = function(){
$http({
url: url_for('account/getinfo'),
method: "POST",
data: fields
}).success(function (data, status, headers, config) {
$scope.locations = data.stores;
$scope.currentLocation = data.stores.filter(function(store){
return store.mpos_id == $scope.mposid;
});
if ($scope.currentLocation.length > 0) {
$scope.currentLocation = $scope.currentLocation[0];
}
}).error(function (data, status, headers, config) {
});
};
the $scope.currentLocation is an Object!
can i use this obj data in other function?
tried with angular.copy and extend, no success
$scope.getInfo = function(){
$scope.currentLocationData = angular.copy($scope.currentLocation);
}
Services in Angular are singletons, so you could store this data in a service and inject it wherever you need it. It's already considered best practice to separate your data requests into services, so you'd be creating a service anyways.
Here's an example:
First separate your data retrieval logic into a service.
angular.module('app').service('accountDataService', AccountDataService);
function AccountDataService($http){
var service = this;
service.getInfo = function(fields){
return $http.post(url_for('account/getinfo'), fields)
.then(function(response){ return response.data.stores; });
}
}
Then create an account service to share the retrieved data between controllers/components:
angular.module('app').service('accountService', AccountService);
function AccountService(accountDataService){
var service = this;
service.currentLocation = {};
service.locations = [];
service.init = function(fields, mposid){
accountDataService.getInfo(fields).then(function(stores){
service.locations = stores;
var currentLocations = stores.filter(function(store){
return store.mpos_id == mposid;
});
if (currentLocations.length > 0) {
service.currentLocation = currentLocations[0];
}
});
}
}
Now all you have to do in your controllers is inject the accountService.
angular.module('app').run(function(accountService){
accountService.init({ /* your fields */ }, '[your mposid]');
});
angular.module('app').controller('myController', MyController);
function MyController($scope, accountService){
$scope.currentLocation = accountService.currentLocation;
}
Running the init function inside run(..) is just for example. You'd preferably run this in a route resolve function or something like that due to the async nature of the init function.
Bonus note
Avoid using the $scope to pass variables to the view. Use the controllerAs syntax instead. You can check the documentation for more info on how it works, or I suggest you to check out the angular 1.x style guide from John Papa.
Definitely you can copy like that i will work. you can check in below example.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app ="app" ng-controller ="ctrl">
{{currentLocationData}}
</div>
<script>
angular.module('app', []).controller('ctrl', function($scope){
$scope.currentLocation = 'testing angular copy';
$scope.currentLocationData = angular.copy($scope.currentLocation);
})
</script>
</body>
</html>
If you are looking to share data between two controllers / directives, then you should use a service and inject it in both the controllers / directives.
If you are looking to just create a new copy of / clone the object, then you can use JSON.parse(JSON.stringify($scope.currentLocation))
Hope this helps!
You can access that object in another scope if and only if that scope is a child not isolated of the previous one. In this case your child scope will inherit all the properties of the parent scope too.
So if that code is the scope of a controller, and you have another controller as child of that one, the child one can access that property.
Although it works, a lot of times that's not the best practice to develop things using AngularJS. It will force a dependency among the two controllers and if you will change your code, you could lose the inheritance and break your code.
In these cases the best solution is to define a service which holds the value of the currentLocation. Then inject this service wherever you need to access this value.
I hope it makes sense
I have a Service:
angular.module('cfd')
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = 'data/people/students.json';
var students = $http.get(path).then(function (resp) {
return resp.data;
});
//save method create a new student if not already exists
//else update the existing object
this.save = function (student) {
if (student.id == null) {
//if this is new student, add it in students array
$scope.students.push(student);
} else {
//for existing student, find this student using id
//and update it.
for (i in students) {
if (students[i].id == student.id) {
students[i] = student;
}
}
}
};
But when I call save(), I don't have access to the $scope, and get ReferenceError: $scope is not defined. So the logical step (for me), is to provide save() with the $scope, and thus I must also provide/inject it to the service. So if I do that like so:
.service('StudentService', [ '$http', '$scope',
function ($http, $scope) {
I get the following error:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <-
StudentService
The link in the error (wow that is neat!) lets me know it is injector related, and might have to do with order of declaration of the js files. I have tried reordering them in the index.html, but I think it is something more simple, such as the way I am injecting them.
Using Angular-UI and Angular-UI-Router
The $scope that you see being injected into controllers is not some service (like the rest of the injectable stuff), but is a Scope object. Many scope objects can be created (usually prototypically inheriting from a parent scope). The root of all scopes is the $rootScope and you can create a new child-scope using the $new() method of any scope (including the $rootScope).
The purpose of a Scope is to "glue together" the presentation and the business logic of your app. It does not make much sense to pass a $scope into a service.
Services are singleton objects used (among other things) to share data (e.g. among several controllers) and generally encapsulate reusable pieces of code (since they can be injected and offer their "services" in any part of your app that needs them: controllers, directives, filters, other services etc).
I am sure, various approaches would work for you. One is this:
Since the StudentService is in charge of dealing with student data, you can have the StudentService keep an array of students and let it "share" it with whoever might be interested (e.g. your $scope). This makes even more sense, if there are other views/controllers/filters/services that need to have access to that info (if there aren't any right now, don't be surprised if they start popping up soon).
Every time a new student is added (using the service's save() method), the service's own array of students will be updated and every other object sharing that array will get automatically updated as well.
Based on the approach described above, your code could look like this:
angular.
module('cfd', []).
factory('StudentService', ['$http', '$q', function ($http, $q) {
var path = 'data/people/students.json';
var students = [];
// In the real app, instead of just updating the students array
// (which will be probably already done from the controller)
// this method should send the student data to the server and
// wait for a response.
// This method returns a promise to emulate what would happen
// when actually communicating with the server.
var save = function (student) {
if (student.id === null) {
students.push(student);
} else {
for (var i = 0; i < students.length; i++) {
if (students[i].id === student.id) {
students[i] = student;
break;
}
}
}
return $q.resolve(student);
};
// Populate the students array with students from the server.
$http.get(path).then(function (response) {
response.data.forEach(function (student) {
students.push(student);
});
});
return {
students: students,
save: save
};
}]).
controller('someCtrl', ['$scope', 'StudentService',
function ($scope, StudentService) {
$scope.students = StudentService.students;
$scope.saveStudent = function (student) {
// Do some $scope-specific stuff...
// Do the actual saving using the StudentService.
// Once the operation is completed, the $scope's `students`
// array will be automatically updated, since it references
// the StudentService's `students` array.
StudentService.save(student).then(function () {
// Do some more $scope-specific stuff,
// e.g. show a notification.
}, function (err) {
// Handle the error.
});
};
}
]);
One thing you should be careful about when using this approach is to never re-assign the service's array, because then any other components (e.g. scopes) will be still referencing the original array and your app will break.
E.g. to clear the array in StudentService:
/* DON'T DO THAT */
var clear = function () { students = []; }
/* DO THIS INSTEAD */
var clear = function () { students.splice(0, students.length); }
See, also, this short demo.
LITTLE UPDATE:
A few words to avoid the confusion that may arise while talking about using a service, but not creating it with the service() function.
Quoting the docs on $provide:
An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function.
[...]
...the $provide service has additional helper methods to register services without specifying a provider:
provider(provider) - registers a service provider with the $injector
constant(obj) - registers a value/object that can be accessed by providers and services.
value(obj) - registers a value/object that can only be accessed by services, not providers.
factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.
service(class) - registers a constructor function, class that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.
Basically, what it says is that every Angular service is registered using $provide.provider(), but there are "shortcut" methods for simpler services (two of which are service() and factory()).
It all "boils down" to a service, so it doesn't make much difference which method you use (as long as the requirements for your service can be covered by that method).
BTW, provider vs service vs factory is one of the most confusing concepts for Angular new-comers, but fortunately there are plenty of resources (here on SO) to make things easier. (Just search around.)
(I hope that clears it up - let me know if it doesn't.)
Instead of trying to modify the $scope within the service, you can implement a $watch within your controller to watch a property on your service for changes and then update a property on the $scope. Here is an example you might try in a controller:
angular.module('cfd')
.controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.students = null;
(function () {
$scope.$watch(function () {
return StudentService.students;
}, function (newVal, oldVal) {
if ( newValue !== oldValue ) {
$scope.students = newVal;
}
});
}());
}]);
One thing to note is that within your service, in order for the students property to be visible, it needs to be on the Service object or this like so:
this.students = $http.get(path).then(function (resp) {
return resp.data;
});
Well (a long one) ... if you insist to have $scope access inside a service, you can:
Create a getter/setter service
ngapp.factory('Scopes', function (){
var mem = {};
return {
store: function (key, value) { mem[key] = value; },
get: function (key) { return mem[key]; }
};
});
Inject it and store the controller scope in it
ngapp.controller('myCtrl', ['$scope', 'Scopes', function($scope, Scopes) {
Scopes.store('myCtrl', $scope);
}]);
Now, get the scope inside another service
ngapp.factory('getRoute', ['Scopes', '$http', function(Scopes, $http){
// there you are
var $scope = Scopes.get('myCtrl');
}]);
Services are singletons, and it is not logical for a scope to be injected in service (which is case indeed, you cannot inject scope in service). You can pass scope as a parameter, but that is also a bad design choice, because you would have scope being edited in multiple places, making it hard for debugging. Code for dealing with scope variables should go in controller, and service calls go to the service.
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
Got into the same predicament. I ended up with the following. So here I am not injecting the scope object into the factory, but setting the $scope in the controller itself using the concept of promise returned by $http service.
(function () {
getDataFactory = function ($http)
{
return {
callWebApi: function (reqData)
{
var dataTemp = {
Page: 1, Take: 10,
PropName: 'Id', SortOrder: 'Asc'
};
return $http({
method: 'GET',
url: '/api/PatientCategoryApi/PatCat',
params: dataTemp, // Parameters to pass to external service
headers: { 'Content-Type': 'application/Json' }
})
}
}
}
patientCategoryController = function ($scope, getDataFactory) {
alert('Hare');
var promise = getDataFactory.callWebApi('someDataToPass');
promise.then(
function successCallback(response) {
alert(JSON.stringify(response.data));
// Set this response data to scope to use it in UI
$scope.gridOptions.data = response.data.Collection;
}, function errorCallback(response) {
alert('Some problem while fetching data!!');
});
}
patientCategoryController.$inject = ['$scope', 'getDataFactory'];
getDataFactory.$inject = ['$http'];
angular.module('demoApp', []);
angular.module('demoApp').controller('patientCategoryController', patientCategoryController);
angular.module('demoApp').factory('getDataFactory', getDataFactory);
}());
Code for dealing with scope variables should go in controller, and service calls go to the service.
You can inject $rootScope for the purpose of using $rootScope.$broadcast and $rootScope.$on.
Otherwise avoid injecting $rootScope. See
Common Pitfalls: $rootScope exists, but it can be used for evil.
I'm trying to pass a Javascript object into my AngularJS controller and having no luck.
I've tried passing it into an init function:
<div ng-controller="GalleryController" ng-init="init(JSOBJ)">
And on my controller side:
$scope.init = function(_JSOBJ)
{
$scope.externalObj = _JSOBJ;
console.log("My Object.attribute : " + _JSOBJ.attribute );
};
Though the above doesn't seem to work.
Alternatively, I've tried pulling the attribute from the AngularJS controller that I am interested in for use in an inline <script> tag:
var JSOBJ.parameter = $('[ng-controller="GalleryController"]').scope().attribute ;
console.log("My Object.parameter: " + JSOBJ.attribute );
Can anyone tell me: what is the best practice regarding this?
I don't have the option to rewrite the plain Javascript object as it is part of a 3rd party library.
Let me know if I need to provide further clarification and thanks in advance for any guidance!
-- JohnDoe
Try setting it as a value:
angular.module('MyApp')
.value('JSOBJ', JSOBJ);
Then inject it into your controller:
angular.module('MyApp')
.controller('GalleryController', ['JSOBJ', function (JSOBJ) { ... }]);
Since your object is a part of third-party library you have to wrap it app in something angular.
Your options are:
if it is jquery pluging init'ed for a DOM node etc you can create a directive
example
myApp.directive('myplugin', function myPlanetDirectiveFactory() {
return {
restrict: 'E',
scope: {},
link: function($scope, $element) { $($element).myplugin() }
}
});
if it is something you need to init you can use factory or service
example
myApp.service(function() {
var obj = window.MyLib()
return {
do: function() { obj.do() }
}
})
if it is plain javascript object you can use value
example
myApp.value('planet', { name : 'Pluto' } );
if it is constant ( number, string , etc) you can use constant
example
myApp.constant('planetName', 'Greasy Giant');
Reference to this doc page: https://docs.angularjs.org/guide/providers
Also I strongly encourage you to read answer to this question: "Thinking in AngularJS" if I have a jQuery background?
If you have JSOBJ accessible via global scope (via window), than you can access it through window directly as in plain JavaScript.
<script>
...
window.JSOBJ = {x:1};
...
</script>
Option 1.
<script>
angular.module('app',[]).controller('ctrl', ['$scope', function($scope) {
$scope.someObject = window.JSOBJ;
}]);
</script>
However it makes the controller code not testable. Therefore $window service may be used
Option 2.
<script>
angular.module('app',[]).controller('ctrl', ['$scope', '$window', function($scope, $window) {
$scope.someObject = $window.JSOBJ;
}]);
</script>
If you want to make some abstraction layer to make your controller agnostic for the source from where you get the object, it is recommended to define service which is responsible for fetching value and then inject it to your controllers, directives, etc.
Option 3.
<script>
angular.module('app',[])
.service('myService', function() {
var JSOBJ = ...; // get JSOBJ from anywhere: localStorage, AJAX, window, etc.
this.getObj = function() {
return JSOBJ;
}
})
.controller('ctrl', ['$scope', 'myService', function($scope, myService) {
$scope.someObject = myService.getObj();
}]);
</script>
Besides of it, for simple values you can define constant or value that may be injected to any controller, service, etc.
Option 4.
<script>
angular.module('app',[]).
value('JSOBJ', JSOBJ).
controller('ctrl', ['$scope', 'JSOBJ', function($scope, JSOBJ) {
$scope.someObject = JSOBJ;
}]);
</script>
In my project i have to create dynamic factory in angular js with dynamic factory name like below
function createDynamicFactory(modId) {
return myModule.factory(modId + '-existingService', function (existingService) {
return existingService(modId);
});
}
I want to get new factory with dynamic name , when i called this function. unfortunately this is not working. how can i achieve this? and how to inject in my controller or in directive dynamically?
You can annotate your service generator like this. It takes the module and extension and then annotates a dependency on the "echo" service (just an example service I defined to echo back text and log it to the console) so the generated service can use it:
makeService = function(module, identifier) {
module.factory(identifier+'-service', ['echo', function(echo) {
return {
run: function(msg) {
return echo.echo(identifier + ": " + msg);
}
};
}]);
};
Then you can make a few dynamic services:
makeService(app, 'ex1');
makeService(app, 'ex2');
Finally, there are two ways to inject. If you know your convention you can pass it in with the annotation as the ext1 is shown. Otherwise, just get an instance of the $injector and grab it that way.
app.controller("myController", ['ex1-service',
'$injector',
'$scope',
function(service, $injector, $scope) {
$scope.service1 = service.run('injected.');
$scope.service2 = $injector.get('ex2-service').run('dynamically injected');
}]);
Here is the full working fiddle: http://jsfiddle.net/jeremylikness/QM52v/1/
Updated: if you want to create the service dynamically after the module is initialized, it's a few slight changes. Instead of trying to register the module, simply return an annotated array. The first parameters are the dependencies and the last is the function to register:
makeService = function(identifier) {
return ['echo', function(echo) {
console.log("in service factory");
return {
run: function(msg) {
return echo.echo(identifier + ": " + msg);
}
};
}];
};
Then you get a reference to the array and call instantiate on the $injector to wire it up with dependencies:
var fn = makeService('ex2');
$scope.service2 = $injector.instantiate(fn).run('dynamically injected');
Here's the fiddle for that version: http://jsfiddle.net/jeremylikness/G98JD/2/