Trouble with Angular Resource Injection - javascript

I'm getting started with the meanjs stack, and have reached a bit of a headscratcher that I don't have the understanding to google properly.
I have the following files:
**
(function () {
'use strict';
angular
.module('students')
.controller('StudentsListController', StudentsListController);
StudentsListController.$inject = ['StudentsService'];
function StudentsListController(StudentsService) {
var vm = this;
vm.students = StudentsService.query();
}
}());
Using this service, I am able to get an array of Student objects in the list-students controller, next:
list-students.client.controller.js
(function () {
'use strict';
angular
.module('students')
.factory('StudentsService', StudentsService);
StudentsService.$inject = ['$resource'];
function StudentsService($resource) {
return $resource('api/students/:studentId', {
studentId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
}());
This works as intended.
What I don't understand, is why when I try to use the same service in another controller, it seems to fail to inject, leaving me with an undefined StudentsServices variable.
What gives?
students.client.controller.js
(function () {
'use strict';
// Students controller
angular
.module('students')
.controller('StudentsController', StudentsController);
StudentsController.$inject = ['$scope', '$state', 'Authentication', 'StudentsService'];
function StudentsController ($scope, $state, Authentication, student, StudentsService) {
var vm = this;
vm.authentication = Authentication;
vm.student = student;
vm.students = StudentsService.query();
...
}());

Your inject is wrong.
'$scope', '$state', 'Authentication', 'StudentsService'
But you're telling the controller to expect
$scope, $state, Authentication, student, StudentsService

I figured it out, per
AngularJS: Factory is always undefined when injected in controller
It was that my injections need to be in the same order as the params passed into the controller function.
Aha!

Related

Angular module loading error

I have an angular project that I'm breaking out into a better file structure but I'm getting Argument 'fn' is not a function, got undefined for an error when creating a new service. Any ideas what I'm doing wrong?
app.js
angular.module('app', [
'app.controllers'
]);
angular.module('app.controllers', ['leaflet-directive', 'app.services']);
angular.module('app.services', []);
main.controller.js
angular.module('app.controllers')
.controller('MainCtrl', MainCtrl);
function MainCtrl($scope, $window, leafletData, DataService) {
var main = this;
main.items = DataService.GetItems();
//Other controller stuff
};
data.service.js
angular.module("app.services")
.factory('DataService', DataService);
var DataService = function(){
return data = {
getItems: function(){
return [//data here];
}
};
}
Your declaration of DataService is the problem. You're declaring it after you're using it. You should change your declaration of DataService to function DataService() instead of setting it to a var to take advantage of function hoisting

Angular: strange behavior with ngCookies

In my Angular app
var mainApp = angular.module('mainApp', ['ngCookies']);
I've defined authCtrl controller:
mainApp.controller('authCtrl', ['$scope, $cookies',function ($scope, $http, $cookies) {
$scope.credentials = {};
$scope.signCheck = function () {
a = $cookies.getObject('session_credentials');
console.log(a);
};
}]);
If I'm removing $scope declaration from array (injection array?)
mainApp.controller('authCtrl', ['$cookies',function ($scope, $http, $cookies) {
$scope becomes undefined.
If I'm removing $cookies — $cookies becomes undefined.
If I keep them both — $injector unknown provider error.
What I'm doing wrong?
Just be sure that you indicate the services in a correct order in the injector array and the controller function params:
Angular docs says:
This is the preferred way to annotate application components. This is
how the examples in the documentation are written.
For example:
someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
// ...
}]);
Here we pass an array whose elements consist of a list of strings (the
names of the dependencies) followed by the function itself.
When using this type of annotation, take care to keep the annotation
array in sync with the parameters in the function declaration.
Perhaps this controller definition will work for you:
mainApp.controller('authCtrl', ['$scope', '$http', '$cookies', function ($scope, $http, $cookies) {
$scope.credentials = {};
$scope.signCheck = function () {
a = $cookies.getObject('session_credentials');
console.log(a);
};
}]);

Angular, injecting own service into provider

So I am working with a provider and injecting some of angular's $log and $location service in the $get to work with them, and this works fine. However when I want to inject my own service into the provider it does not seem to work.
Here's what I mean - I can inject the angular $log and $location like so (in the provider)
this.$get = $get;
$get.$inject = ['$log', '$location'];
function $get( $log, $location) {
return {
setModule: function(name, cb) {
},
getModules: function() {
}
}
}
But, I have a service below like
.service("myService",function(){
this.sayHello = function() {
return "Hello, World!"
});
And try to inject it like
$get.$inject = ['myService', '$log', '$location'];
function $get(myService, $log, $location) {
When I call myService in the provider, it comes back undefined.
Is there any reason I can call the angular($) stuff and not my own to inject into the provider?
Thanks!
Edit : So after I inject it I try and use it inside the $get like
$get.$inject = ['myService', '$log', '$location'];
function $get(myService, $log, $location) {
return {
test: function(){
console.log(myService);
}
}
returns undefined
1) pass $injector as a dependency in the controller ['$injector']
2) call $injector.get to instantiate the service by name
$scope.service = $injector.get(servicename);

AngularJS UI-Router won't recognize a defined controller on the module

I'm in the process of learning Angular, and I'm trying to set up a state with a controller using ui-router. I have a main module named app.js, and then sub-modules based on different content.
The first sub-module is diary.js. Everything is working with this controller other than the controllers. The state works in the UI, etc. When I make the controller directly in diary.js (such as controller : function () { //stuff }, it works fine). But when I try to include an already defined controller for the diary state (like it's currently written), I get the following error (I couldn't post the whole error because stackoverflow won't let me have that many links):
"Error: [ng:areq]
errors.angularjs.org/1.2.23/ng/areq?p0=DiaryCtrl&p1=not%20aNaNunction%2C%20got%20undefined
at Error (native) ...
/** diary.js */
'use strict';
(function () {
angular.module('diary', ['ui.router'])
.config(['$stateProvider', function ($stateProvider) {
// States
$stateProvider.state('diary', {
url : '/diary',
templateUrl : 'diary/html/diary.html',
controller : 'DiaryCtrl'
});
}]);
}).call();
Here is the code for the DiaryCtrl.js (the defined controller).
/** DiaryCtrl.js */
'use strict';
angular.module('diary')
.controller('DiaryCtrl', [$scope, $http, function ($scope, $http) {
$http.get('api/json/diaries.html').success(function (data) {
$scope.diaries = data;
}).error(function (status) {
console.log(status);
});
}]);
I'd appreciate any help. Let me know if you need more information.
I am fairly certain it is because your injections ($scope & $http) in the DiaryCtrl are not strings:
.controller('DiaryCtrl', [$scope, $http, function ($scope, $http)
should be:
// Notice the added quotations around the scope and http injections in the array
.controller('DiaryCtrl', ['$scope', '$http', function ($scope, $http) {

update angular model from a service

angular.module('app.services', []).service("test", function($http, $rootScope){
this.test=function(){
$rootScope.name="test1";
};
};
angular.module('app.controllers', []).controller('TestController', function ($scope, test) {
test.send();
})
I dont get an error but the changes don't get applied to the UI. I tried $scope.apply() and got an error.
We need to tell Angular which modules your module depends on, In our case the main module is app.controllers.
To call service from different model we need tell to controller where is our service:
['app.services']
JS
var appServices = angular.module('app.services', []);
var appCtrl = angular.module('app.controllers', ['app.services']);
appServices
.service("test", function ($http, $rootScope) {
this.send = function () {
$rootScope.name = "test1";
};
});
appCtrl.controller('TestController', function ($scope, test) {
test.send();
});
Demo Fiddle
I think you should change ".service" by ".factory".
As I can see in the creating services docs there are 3 ways of creating custom services. One of then is using factory way, as the following:
var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
Hope to help.

Categories

Resources