Angularjs injecting factory with http to a controller - angularjs

I keep getting errors while injecting a factory in to a controller. It worked in a case where the controller is simple. It fails when the page and the controller has special components like ng-flow or ng-grid.
var carouselController = carouselApp.controller('carouselController', ['CMSFactory', function ($scope,CMSFactory) {
// MY CODE HERE...
}
var CMSServices = angular.module('api.services', [ 'ngResource' ]);
CMSServices.factory('CMSFactory', function($http, $q) {
var CMSService = {};
CMSService.saveSiteInfo = function(data) {
// MY CODE HERE...
};
CMSService.addSlide = function(data) {
// MY CODE HERE...
};
return CMSService;
});
I get TypeError: undefined is not a function error. If I remove the factory injection code works fine.
Appreciate any help...

You're not declaring $scope in your array of dependencies:
Change:
var carouselController = carouselApp.controller('carouselController', ['CMSFactory', function ($scope,CMSFactory) {
To:
var carouselController = carouselApp.controller('carouselController', ['$scope', 'CMSFactory', function ($scope,CMSFactory) {

Related

Angular-service TypeError: Cannot read property 'saveURL' of undefined

I am trying to write a service to store query string of a URL. I am doing so by storing it in a cookie and then retrieving it. But when i try to access the saveURL method from the controller to add the query string, I am getting this error:
TypeError: Cannot read property 'saveURL' of undefined
controller.js
angular
.module("app.alerts.alertView")
.controller("AlertViewsController", AlertViewsController);
AlertViewsController.$inject = [
"$scope", "$location", "alertHistory"
];
function AlertViewsController($scope, $location, alertHistory) {
alertHistory.saveURL($location.search());
}
service.js
(function () {
"use strict";
angular
.module("app.alerts.alertView")
.service("alertHistory", alertHistory);
alertHistory.$inject = [
"$cookieStore"];
function alertHistory ($cookieStore) {
return {
saveURL: function (urlObj) {
var array = $cookieStore.get("key");
array.push(urlObj);
$cookieStore.put("key", array);
}
};
}
})();
I have injected the service correctly. What else can i correct to solve the error. Please help
What it looks like is happening is that you are not returning what you think you are returning because the return object is not concrete enough for JS to hang on to. Also, you forgot to inject the $location service. I would try rewriting it as follows:
angular
.module("app.alerts.alertView")
.service("alertHistory", [ '$cookieStore', function ($cookieStore) {
var x = {};
x.saveURL = function (urlObj) {
var array = $cookieStore.get("key");
array.push(urlObj);
$cookieStore.put("key", array);
};
return x;
}]).controller('AlertViewsController', [ '$scope', '$location', 'alertHistory', function ($scope, $location, alertHistory) {
alertHistory.saveURL($location.search());
}]);

Injecting $http in angular - Cannot read property 'get' of undefined

I am trying to make an http call function in angular. The problem is that when I try running this on the Chrome console, it says "cannot read get of undefined." Obviously this is referring to the http get call, but it really looks to me like the http dependency was injected, so I am not sure what I am missing.
angular.module('app').controller("MainController", function($http, $scope ){
var vm = this;
vm.title = 'title';
vm.input = '';
$scope.submit = function (input, $scope, $http) {
$http.get("insert-url-here")
.success(console.log(input));
}
}
maybe you have some syntax error.
last time i worked with angular and the $http service i did something like this:
angular.module('app').controller('MainController', ['$scope', '$http', function($http, $scope ){
var vm = this;
vm.title = 'title';
vm.input = '';
$scope.submit = function (input) {
$http.get("insert-url-here")
.success(function(responseData) {
console.log(input));
});
}
//console.log(vm.input);
}]
You don't want to inject $scope and $http in your function. Injecting into you controller is sufficient. Should look like this:
$scope.submit = function (input) {
$http.get("insert-url-here")
.success(console.log(input));
//console.log(vm.input);
})]

Correct way to make a factory module in angularJs

I have a controller function like this:
$scope.localTimezone = function (userTimezone,datetime) {
// ....
return data;
}
What is the correct way to make it a factory module? I tried the following but it's giving errors.
angular.module('localTimezone', [])
.factory('localTimezone',function(userTimezone,datetime) {
// ...
return data;
});
angular.module('app', ['localTimezone'])
.controller('tasksController',function ($scope,localTimezone) {
// ...
});
I am missing out on some concept or logic.Can anyone please point me in the right direction?
CONTROLLER Example
Bad:
function MainCtrl () {
this.doSomething = function () {
};
}
angular
.module('app')
.controller('MainCtrl', MainCtrl);
Good:
function MainCtrl (SomeService) {
this.doSomething = SomeService.doSomething;
}
angular
.module('app')
.controller('MainCtrl', MainCtrl);
Factory Example
Bad:
function AnotherService () {
var someValue = '';
var someMethod = function () {
};
return {
someValue: someValue,
someMethod: someMethod
};
}
angular
.module('app')
.factory('AnotherService', AnotherService);
Good:
function AnotherService () {
var AnotherService = {};
AnotherService.someValue = '';
AnotherService.someMethod = function () {
};
return AnotherService;
}
angular
.module('app')
.factory('AnotherService', AnotherService);
For Detail Guidelines go through this blog :
Opinionated AngularJS styleguide for teams
Here is a working code example based on the assumption userTimezone and datetime are services which are apart of the localTimezone module.
The following has been modified
'data' which your factory is returning has been modified to return a string based on the factory pattern - as you were returning 'data' which referenced nothing
constructing the app has been moved to the top. This code should execute before anything else.
app variable removed - I don't like global variables.
Code:
angular.module('app', ['localTimezone']);
angular.module('localTimezone', []).factory('localTimezone',
function(userTimezone, datetime) {
var data = 'hello';
return { data: data } ;
});
angular.module('localTimezone').service('userTimezone', function() {
});
angular.module('localTimezone').service('datetime', function() {
});
angular.module('app').controller('tasksController',function ($scope,localTimezone) {
});
Codepen: http://codepen.io/anon/pen/wijmb (no errors appearing in console)
Take a look at http://angular-tips.com/blog/2013/08/understanding-service-types for information about the different service types in Angular.

Angularjs - Invoke Function from module.config

I have a code of
var viewerAngular = angular.module('ngAppDemo', ['restangular','btford.socket-io'])
.config(function(RestangularProvider) {
$.get('../config/config.xml',
function(data) {
$(data).find('contentserver').each(function() {
serverDetails.contentserver = assignServerDetails($(this));
var restprovider = RestangularProvider;
restprovider.setBaseUrl("http://"+serverDetails.contentserver.ip+":"+serverDetails.contentserver.port+"\:"+serverDetails.contentserver.port);
//$scope.init();
});
});
I need to invoke function init(), after reading the config(../config/config.xml) file.
I got an error of ReferenceError: $scope is not defined.
How can I add $scope in module.config? Or How can I call function from config?
If you need to add something to every scope in config, you can use $rootScope, but it's better practice to create a service for that data.
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('app', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
var viewerAngular = angular.module('ngAppDemo', ['restangular','btford.socket-io'])
.config(function(RestangularProvider) {
$.get('../config/config.xml',
function(data) {
$(data).find('contentserver').each(function() {
serverDetails.contentserver = assignServerDetails($(this));
var restprovider = RestangularProvider;
restprovider.setBaseUrl("http://"+serverDetails.contentserver.ip+":"+serverDetails.contentserver.port+"\:"+serverDetails.contentserver.port);
var Scope=angular.element(document.querySelector('[ng-controller="controllerName"]')).scope();
Scope.init();
});
});

AngularJS factory not working

I have abstracted my working code from a controller into a factory, but it doesn't seem to be working and I can't find what's wrong. I opted for a factory rather than a service because I wanted to execute some code that defined the variable before returning that variable; I want to get result.station (a part of the data returned by the API), not the full result.
This is my code:
var app = angular.module("myApp", []);
app.factory('api', ['$http',
function($http) {
var station_list = [];
$http({
method: 'GET',
url: 'http://api.irail.be/stations/?format=json&lang=nl'
})
.success(function(result) {
station_list = result.station;
});
return {
Stations: function() {
return station_list;
}
};
}
]);
app.controller("myController", ['api', '$scope',
function(api, $scope) {
$scope.station_list = api.Stations();
$scope.title = "Stations";
}
]);
and a working example.
Try this:
.success(function(result) {
angular.copy(result.station, station_list);
});
You had a small error, you were replacing the array instead of populating it. I used angular.copy instead of the assignment in your factory and it works
http://plnkr.co/edit/sqgKcFZAcClmkfdXHhrz
The problem is that you are dealing with asynchronous nature of AJAX.
I would suggest to have a delegate method in controller, which will be called when the service call is complete.
Something like the following:
app.controller("myController", ['api', '$scope',
function(api, $scope) {
api.Stations( function(station_list) {
$scope.station_list = station_list;
});
$scope.title = "Stations";
}
]);
The following is a service method excerpt:
return {
Stations: function(delegate) {
if (delegate)
delegate(station_list);
return station_list;
}
};

Resources