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

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) {

Related

Dependency injection hell, what is expected?

I'm trying to separate components into several files for a simple application but angular's dependency injector is giving me headaches and I don't really know what is expected.
Unknown provider: servicesProvider <- services <- maincontroller
Is the error I'm getting.
app.js
//Application definition with injected dependencies
var app = angular.module('leadcapacity', ['services', 'utils', 'customfilters', 'controllers']);
services.js
var services = angular.module('services', []);
services.service('xrmservice',
[
'$http', function($http) {
var oDataUrl = Xrm.Page.context.getClientUrl() + '/XRMServices/2011/OrganizationData.svc/';
var service = {};
service.query = function(entitySet, query) {
return $http.get(oDataUrl + entitySet + '?' + query);
};
return service;
}
]);
controllers.js
var ctrls = angular.module('controllers', ['utils', 'services']);
ctrls.controller('maincontroller',
function ($scope, services, utils) {
};
});
And the include order in index.html
<script src="service.js"></script>
<script src="controllers.js"></script>
<script src="app.js"></script>
Looks fine to me. I know this is perhaps not the best way to organize things, but getting a "Hello world" first would be nice.
Thanks.
Error message appearing in console clearly says that, services
dependency isn't exists in the module.
You have injected incorrect service name in maincontroller controller factory function, basically you were trying to to inject services(module name) instead of xrmservice(service name)
function ($scope, services, utils) {
should be
function ($scope, xrmservice, utils) {
Additional
Do follow Inline Array annotation of DI, as you were already used the same in your xrmservice service JS file, so that in future you don't need to go back and change that when you face javascript minification related issues.
Controller
ctrls.controller('maincontroller', [ '$scope', 'xrmservice', 'utils',
function ($scope, xrmservice, utils) {
//code goes here
//....
};
}]);
Although you have injected them into the module, you need to give them to the function so you can use the injected modules
ctrls.controller('maincontroller',
['$scope', 'services', 'utils', function ($scope, services, utils) {
};
}]);

Trouble with Angular Resource Injection

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!

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);
};
}]);

AngularJS : controller with factory

I am new to Angular and I am creating my first app right now. I have a factory in place and my controller should be pulling in data from my source, however I keep on getting this error. My factory is called SpreadsheetFactory.
I have the code for my controller below. Any help is appreciated, thanks!
(function () {
angular
.module('beerApp')
.controller('appController', appController, ['$scope', 'SpreadsheetFactory']);
function appController($scope, SpreadsheetFactory) {
SpreadsheetFactory.getData().then( function (data) {
console.log(data)
});
// $scope.brews = [];
return data;
}
})();
This line is wrong:
.controller('appController', appController, ['$scope', 'SpreadsheetFactory']);
It should be:
.controller('appController', ['$scope', 'SpreadsheetFactory', appController]);

Displaying data with AngularJS loaded by NodeJS

I'm building my first MEAN twitter like application and currently try to display a list of posts to the gui. what I currently do is:
The angular.js part:
in my main.js:
angular.module('MyApp')
.controller('MainCtrl', ['$scope', 'Feed', function($scope, Feed) {
$scope.feeds = Feed.showFeeds();
// ...
}
in my feed.js:
angular.module('MyApp')
.factory('Feed', ['$http', '$location', '$rootScope', '$cookieStore', '$alert', '$resource',
function ($http, $location, $rootScope, $cookieStore, $alert, $resource) {
return {
// other functions like addFeed: function(f) {...},
showFeeds: function() {
return $http.get('/api/feeds');
}
The node.js part:
app.get('/api/feeds', function (req, res, next) {
var query = Feed.find();
query.limit(8);
query.exec(function (err, feeds) {
if (err) return next(err);
res.send(feeds)
// feeds is a corret JSON with all my data at this point
});
});
and my home.html:
<p>{{ feeds }}</p> <!-- for testing - this just returns {} -->
<div ng-repeat="feed in feeds">
<div>
{{feed.feedMessage}}
</div>
So my problem is: Everything loads fine, but nothing renders out on the page, I don't get any errors, just my $scope.feeds object is empty. I'm pretty new to this, so maybe it's an obvious bug, but if someone could point me in the right direction, that would be great!
Right now you are returning a promise, and you need to be accessing the data.:
Feed.showFeeds().success( function(data) {
$scope.feeds = data.feeds;
});
The '$http' service provided by angular return always an instance of '$q', another angular service which allows us to use the Promise syntax for all async commands.
When you assign the return of Feed.showFeeds() to your scope variable, you bind a promise to your view and Angular can't display it.
You should use the success method provide by $http in order to get the server data and bind them to your scope variable like bencripps said.
Note: The success method (and error) are specific methods of $http and call the $digest method of angular which triggers a refresh of the view automatically.
angular.module('MyApp')
.controller('MainCtrl', ['$scope', 'Feed', function($scope, Feed) {
$scope.feeds = [];
Feed.showFeeds().success(function(data) {
//depends of the json return
//try a console.log(data)
$scope.feeds = data.feeds
});
// ...
}

Categories

Resources