How can I console $rootScope before each controller in angular? - angularjs

I'm working on debug step. There are several pages. Each time, I would need console the $rootScope for debug. I want to know if there is a way to console log the $rootScope for all controller? In other words, How can I console $rootScope before each controller in angular?
Update:
I mean the statement should run before all controllers without modify the controllers.

If you are using angular routing, you can use:
angular.module('myModule').run([ '$rootScope', function($rootScope) {
$rootScope.$on("$locationChangeStart", function() {
console.log($rootScope);
});
} ]);
And if you re using ng-view you can instead listen for $viewContentLoaded

Before execute route change locationChangeStart, still if you want to console it, then you can console or initialize it from main controller first.
var app = angular.module('app', ['ngRoute']);
app.controller('MainController', ['$scope', '$rootScope', 'myServices', function ($scope, $rootScope, myServices) {
$rootScope.test = 'Hello World';
console.log($rootScope.test);
}]);

Related

Service function not found in angular app

I added a service to my angular controller, but it says every time there is no function. I really dont know why and hope there is someone who can help me.
Here is my userCtrl.js http://hastebin.com/imufehimaw.js
You haven't injected the service in controller
Change
controller('userCtrl', function($scope, $http) {
To
controller('userCtrl', function($scope, $http, ergastAPIservice) {
You should inject your service as a dependency to your controller as shown below before using it
controller('userCtrl', function($scope, $http, ergastAPIservice) {
//your code
});
better way of using it if you are considering minimizing in future
controller('userCtrl', ['$scope', '$http', 'ergastAPIservice', function($scope, $http, ergastAPIservice) {
//your code
}]);

Angular's $interval service not found when testing using karma and mocha

I created a service that has $interval as a dependency and makes use of it and seems to work. Unfortunately when I'm trying to unit test the app $interval service is not found by angular:
Unknown provider: $$qProvider <- $$q <- $interval
I am not calling the service inside a controller as usual, but on the run() method of the app:
app.service('myService', ['$rootScope', '$window', '$interval', myService]);
app.run(function (myService) {
...
});
It works, but if I try to test the app crashes. Rest of angular services don't seem to have this problem ($window, $location, $rootScope, ...) and even this same service works if I attach my service to a controller instead than calling it at app.run():
app.controller('myController', ['myService', function(myService){ ... }]);
I use Karma+Mocha+Sinon+Chai to test.
UPDATE
Example with mini app trying to use $interval at app.run():
var anApp = angular.module('myTestApp', ['ngRoute']);
anApp.run(function($rootScope, $timeout, $window, $location, $interval) {
// blah
});
The test:
describe("Lalarala", function() {
var scope = null;
beforeEach(function() {
module("myTestApp");
inject(function ($rootScope) {
scope = $rootScope.$new();
});
});
it("doesnt crash", function () {
//blah
});
});
Note: If you remove $interval from the app.run() it works. Instead, other angular services like $timeout, $window or $location don't seem to bother.
Also, I've noticed that other services like $resource have this problem too.
I presume some of those services require something else to be there before they are ready and that's why I can't call them at app.run()?
Thanks for any help.
This line is definitely wrong.
app.controller('myController', [myService, function(myService){ ... }]);
Array injection syntax should contain strings
app.controller('myController', ['myService', function(myService){ ... }]);
Ok,
After checking many things I found the problem had to do with an angular-mocks being out of date.
I updated versions of angular and angular-mocks and now everything is working fine.
Sorry!

Getting controller undefined when trying to run jasmine test

I'm just about to write tests for my angularjs-app. However when Im trying to run the test which is very simpel one i get the following error.
Error: [ng:areq] Argument 'MyPageController' is not a function, got undefined
I'll provide code for the setup of my controllers, config etc.
Route
var myPageApp = angular.module('myPageApp', ['ngRoute', 'ngAnimate', 'ngSanitize', 'app.controller', 'app.service', 'app.filter', 'app.config'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'App_AngularJs/partials/myPage/myPage.htm',
controller: 'MyPageController',
reloadOnSearch: false,
});
}]);
Controller
var myPageApp = angular.module('app.controller', ['oci.treeview', 'ui.bootstrap'])
.controller('MyPageController', ['$scope', '$routeParams', '$location', '$timeout', '$filter', '$modal', 'myPageService',
function ($scope, $routeParams, $location, $timeout, $filter, $modal, myPageService) {
init();
function init() {
$scope.page = { value: $routeParams.page || 1 };
}
}]);
Simpel test
'use strict';
describe('Testing MyPageController', function(){
var scope;
//mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('myPageApp'));
//mock the controller for the same reason and include $rootScope and $controller
beforeEach(angular.mock.inject(function($rootScope, $controller){
//create an empty scope
scope = $rootScope.$new();
//declare the controller and inject our empty scope
$controller('MyPageController', { $scope: scope });
}));
// tests start here
it('should map routes to controllers', function () {
module('myPageApp');
inject(function ($route) {
expect($route.routes['/'].controller).toBe('MyPageController');
expect($route.routes['/'].templateUrl).
toEqual('App_AngularJs/partials/myPage/myPage.htm');
});
});
it('should have variable assigned = "1"', function(){
expect(scope.page.value).toBe(1);
});
});
My wildest and best guess is that i need to mock app.controller but how? Everything starts out with myPageApp which holds references to service, controller etc etc..
I think your issue is that routing and the controller are trying to load different modules viz "myPageApp" and "app.controller" and in your test with beforeEach you are trying to load 'myPageApp' module to which router is associated but not the controller.
So it seems to me that either you use same module for both router and controllers. Or try loading both modules in the test. Still I believe associating the router and controller with same module makes more sense.
An small example as below. Extract the application module in common js file (may be call it app.js)
var myApp = angular.module(
'myApp');
Now define router as
myApp.config(function ($routeProvider) {
$routeProvider
.when('/testUrl', {
templateUrl: '/myApp/views/test-view',
controller: 'TestViewController'
})
Similary define controller as
myApp.controller('TestViewController',[your dependencies goes here])
And now in your tests
beforeEach(module('myApp'));
This will work for sure. Hope it helps.

Using factory within controller in angularjs

I have simple module with controller and factory. I want to use factory within my controller.
So I should add the name of factory within my function() of controller. Adding this, so my controller doesnt work anymore (blank page, no errors)
var app = angular.module('main', ['ngAnimate'])
app.factory('Socket', function($scope) { ... });
My controller works if:
app.controller('DemoCtrl', function($scope, $http, $filter, ngTableParams, $timeout) {...});
My controller does not work if:
app.controller('DemoCtrl', function($scope, $http, $filter, ngTableParams, $timeout, Socket) {...});
Can anyone help me on this?
You can't insert $scope into a service in angular, because it has no meaning in the context of services. $scope is for controllers only, so remove the $scope dependency from your service:
app.factory('Socket', function() { ... });

updating ng-model of one angular js controller from another angular js controller

Angular Experts,
I am new to Angular Js and trying to update input in one controller with value from the input in another controller. I am not sure whether it is even possible or not?
I have created js fiddle link just to give an idea.
http://jsfiddle.net/MwK4T/
In this example when you enter a value in controller 2's input, and click 'Set Value it does update biding with <li></li> but does't not update input of the controller 1.
Thanks in advance
I made it working using $broadcast. And it is working like a charm.
I did something like this.
App.controller('Ctrl1', function($rootScope, $scope) {
$rootScope.$broadcast('msgid', msg);
});
App.controller('Ctrl2', function($scope) {
$scope.$on('msgid', function(event, msg) {
console.log(msg);
});
});
Thanks for helping me out.
Best way would be to use the service, we need to avoid the event as much we can, see this
var app= angular.module('testmodule', []);
app.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
app.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
app.service('myservice', function() {
this.xxx = "yyy";
});
Check the working example

Resources