How do I print $rootScope variable? - javascript

This code is not working:
<td><img src="{{$rootScope.s3BucketUrl}}"/></td>
and this is where it's defined:
var appCtrl = app.controller('AppCtrl', function($scope, $resource, $location, $route, sharedProperties, $q, $rootScope){
defer = $q.defer();
//$rootScope.s3BucketUrl = 'http://lynd.s3.amazonaws.com/';//comment below one when live
$rootScope.s3BucketUrl = 'http://lynd-test.s3.amazonaws.com/';
//code omitted
});
AppCtrl is bound first on body tag.
Could anybody please suggest how do I print $rootScope variable?

Just use {{s3BucketUrl}} and you would get the value.
Your current scope is a child scope of rootscope and hence you can always access the elements of rootscope.
This wiki is highly recommended

Related

Using Cookie value from one ng-app in another ng-app in AngularJS

I know that it isn't good practice to have multiple ng-apps in a project but my project is divided into segments that aren't generally related to each other, plus I am left with more or less no other option.
My problem is the persistence of ng-cookie amidst two separate Javascript files. Let's say I have dashboard1.html that is linked to controller1.js and dashboard2.html linked to controller2.js.
Now, I want to access the cookie value of controller 1 in controller 2. When I try to do this the result says undefined and that means I cannot access the cookie value set by another Javascript file.
Please advise me how to solve this issue.
NOTE : Javascript files have respective ng-app defined and controller for each application.
This is Controller and ng-app part of one module.
var app = angular.module('mainpageapp', ['ngRoute','ngCookies']);
app.controller('ctrlmainpage', ['$scope', '$timeout','$http', '$route', '$routeParams', '$location', '$rootScope', '$cookies', function ($scope, $timeout, $http, $route, $routeParams, $location, $rootScope, $cookies) {
console.log("Csadad");
$cookies.myFavorite = 'TestCookie';
var favoriteCookie = $cookies.myFavorite;
console.log("Cookie" + favoriteCookie);
Now in this ng-app's controller I am setting a cookie, it works properly and I do get expected response on console. This is in file controller1.js
Now I am trying to access the same cookie in controller2.js that is all together bound by different ng-app.
var app = angular.module('myApp', ['ngRoute', 'smart-table', 'ngCookies']);
var id = 'hasdh';
app.controller('dashmerctrl', ['$scope', '$timeout','$http', '$route', '$routeParams', '$location', '$rootScope', '$cookies', function ($scope, $timeout, $http, $route, $routeParams, $location, $rootScope, $cookies)
{
var favoriteCookie1 = $cookies.myFavorite;
console.log("Cookie1" + favoriteCookie1);
Her I get undefined as output.
I want to access that same cookie in this file.
if you wish to share data across tabs or domains you can give zendesk's "cross-storage" a try, just implemented it with AngularJS and it works like a charm.
it utilizes window.postMessage() technique to achieve this behavior.
link: zendesk/cross-storage

$scope is not defined in service AngularJs:

got error of scope not defined when i use for response message:
$scope.responsemessage = response;
then I added $scope here like this:
app.service('fileUpload', ['$http', '$scope', function ($http, $scope) {
When I added above $scope got this error Error: [$injector:unpr]
http://errors.angularjs.org/1.4.8/$injector/unpr?p0=.................
Service don't have scope.
If you wanna to use scope inside service , have to pass it from controller .
Like this
In controller
fileUpload.checkFile($scope.responsemessage);
In service
function checkFile(respMsg)
{
console.log(respMsg);
}
$scopes are not available from services, it should only be used inside controllers.
In angular $scope is available in controllers and services are used as a dependency for data provider.
You just can't use $scope in the service and from service you can return a promise object like:
app.service('fileUpload', ['$http', function($http) {
return $http.post('url')
}]);
Now you can inject this service to update a variable on the controller's $scope:
app.controller('cntrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.responsemessage = fileUpload.then(function(data){
return data;
})
}]);
You can not use $scope in Services as well as in Factories.
You can call service by giving $scope value as a parameter and save the return value to the $scope variable

AngularJS: Inject controller inside another controller from the same module

Is possible to inject a controller into another controller that is part of the same module?
example:
var app = angular.module('myAppModule', [])
.controller('controllerOne', ['$scope', function($scope){
$scope.helloWorld = function(){
return 'Hello World';
}
}])
.controller('controllerTwo', ['$scope', 'controllerOne', function($scope, controllerOne){
console.log(controllerOne.helloWorld());
}])
I keep getting unknown provider on controllerOne. I don't see how that's possible since they coexist in the same module. Any help would be much appreciated.
You need to use $controller dependency by using that you can inject one controller to another
.controller('controllerTwo', ['$scope', '$controller', function($scope, $controller){
$controller('controllerOne', {$scope: $scope})
//inside scope you the controllerOne scope will available
}]);
But do prefer service/factory to share data
Move your logic into a "service" (either a factory/service/provider). I personally prefer factories, I just like controlling my own object instead of using this or anything like that with the other options.
Using a service, you give yourself the ability to abstract business logic from your controllers, and make that logic -- reusable -- !
var app = angular.module('myAppModule', [])
// typically people use the word Service at the end of the name
// even if it's a factory (it's all the same thing really...
.factory('sharedService', function () {
var methods = {};
methods.helloWorld = function () {
return 'Hello World!';
};
// whatever methods/properties you have within this methods object
// will be available to be called anywhere sharedService is injected.
return methods;
})
Notice sharedService is injected
.controller('ControllerOne', ['$scope', 'sharedService', function($scope, sharedService) {
$scope.helloWorld = sharedService.helloWorld();
}])
// Notice sharedService is injected here as well
.controller('ControllerTwo', ['$scope', 'sharedService', function($scope, sharedService){
// Now we can access it here too!
console.log( sharedService.helloWorld() );
}]);
Side note : Controllers should be capitalized to show their significance!
The power of services :)
If the a controllerTwo needs to call the same function as controllerOne, you may want to create a service to handle it. Angular Services - they are accessible throughout your program through dependency injection.
var app = angular.module('myAppModule', [])
.controller('controllerOne', ['$scope', 'Hello', function($scope, Hello){
console.log(Hello.helloWorld() + ' controller one');
}])
.controller('controllerTwo', ['$scope', 'Hello', function($scope, Hello){
console.log(Hello.helloWorld() + ' controller two');
}])
.factory('Hello', [function() {
var data = {
'helloWorld': function() {
return 'Hello World';
}
}
return data;
}]);
Hope this helps!
You cannot inject controllers in another controllers,only serviceProviers are injectable.That's the reason you are getting error as unkown provider in controller one.
Use Services instead and inject them in controllers,if there is some come functionality to be shared among controllers.Services are the best way to share data in between controllers.
You can declare a variable or function or say object on $rootScope, it's exists in your whole application.
Share data between AngularJS controllers

Accessing $rootScope methods in Controller

In this ng-book JSBin, does $scope.$watch() resolves to $rootScope.$watch() due to prototypal inheritance.
Can we inject $rootScope explicitly inside the controller so that $scope would be same as $rootScope inside the controller, without going through prototypal inheritance?
Replicating code here for reference:
// open this example and type person.name into the test field
angular.module('myApp', [])
.controller('MyController',
['$scope', '$parse', function($scope, $parse) {
$scope.person = {
name: "Ari Lerner"
};
$scope.$watch('expr', function(newVal, oldVal, scope) {
if (newVal !== oldVal) {
// Let's set up our parseFun with the expression
var parseFun = $parse(newVal);
// Get the value of the parsed expression, set it on the scope for output
scope.parsedExpr = parseFun(scope);
}
});
}]);
Just inject it the same way as $scope or $parse, anything defined on $rootScope will be then accessible inside your controller.
app.controller('MyController', ['$scope', '$parse', '$rootScope',
function($scope, $parse, $rootScope) {
$rootScope.foo();
console.log($rootScope.bar);
}
]);
etc.
If you intend to use the rootScope so badly, it has a provider just as scope does. Including '$rootScope' into your controller as you do with the '$scope' does the trick.
There's also the $parent attribute of the $scope which could come in handy, but IMO it tends to make code less maintainable if abused. In particular when multiple scopes are nested, as you need to traverse the whole hierarchy.

Get $scope reference on $rootScope event handler

In the .run section of the main module of my application, I have an event handler for the $locationChangeStart event. I want to use this in order to confirm discarding unsaved changes. The problem is that I need a reference to the $scope in order to perform these checks.
I tried adding that reference as I added the one for the $rootScope, but I get an error Uncaught Error: Unknown provider: $scopeProvider <- $scope.
How should I proceed to this? I am open for alternatives.
.run(['$rootScope', '$location', function ($rootScope, $location) {
$rootScope.$on("$locationChangeStart", function (event, next, current) {
if ($scope.unsavedChanges && !confirm('Unsaved changes') {
event.preventDefault();
}
});
}
You can only inject instances (not Providers) into the run blocks. This is from the doc of module.
angular.module('myModule', []).
run(function(injectables) { // instance-injector
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// into the run blocks
});
So you won't be able to inject $scopeProvider.
You could inject $scope to your function like;
.run(['$rootScope', '$location', '$scope', function ($rootScope, $location, $scope)

Categories

Resources