Angular JS - Sending data from a directive to a parent controller - angularjs

I have an app where I use the ngCart directive in order to store the items added to a basket. The problem is that this directive just has the functionality of sending the information about the items added by the user, but I would need also to send some information that I would get from a form.
So in order to send it in a single object, I need first to extract the data stored in the directive to my main scope, and then merge it with the data I get from the form.
For that I need to modify the ngCart.js directive. I tried to make a service, as adviced here, but I don't get to get it working. The code I added to the directive is this
.service('ngCartData', ['ngCart', function(ngCart){
return {
data:ngCart;
};
}])
, but I get an error saying Module 'ngCart' is not available!
I'm totally new to services and factories in angular, so I don't know exactly where to look to make it work. I made a plunkr with my code (I tried modifying the ngCart.js file with the code above, but the plunkr shows the directive without any modification). I just need to be able to send the data stored in the directive in the scope ngCart so that I can listen to it in the parent controller (see the checkout section in the plunkr).
Any help would be much appreciated. Thanks!

did you load the js file like this :
<script src="pathto/angular/angular.js"></script>
<script src="pathto/ngCart.js"></script> or ngCart.min.js
did you load the module in your declaration module like this ? :
var myApp = angular.module('myApp',['ngCart']);

You actually have this backward. You can't inject a directive into a service. You must inject the service into the main controller and into the directive so that you can use it as a bridge between the two. Services are singletons so if you modify the properties of a service those modifications will be available anywhere else it is asked for.
Your service will look something like this:
.service('ngCartData', [function(){
return {
data:[],
addData: function(newData){
this.data.push(newData);
},
getData: function(){
return this.data;
}
};
}])
then in your controller and directive use the ngCartData api, which would look something like this:
$scope.someData = ngCartData.getData();
$scope.someFunction = function(dataToStore){
ngCartData.addData(dataToStore);
};

You had the right idea in mind, and I'm surprised it didn't work for you.
I have edited your app in the following way (in script.js)
app.controller('myCtrl', function($scope, ngCart, myCart) {
$scope.names = [...];
...
console.log(myCart.cart);
})
.factory('myCart',function(ngCart){
return {
cart: ngCart.$cart
};
})
and it logged {shipping: 30, taxRate: null, tax: null, items: Array[2]}, which I think is what you need (I added 2 items before it logged).
Notice that adding a the service is redundant; The data is accessible whenever and wherever you need. Just inject ngCart to your controller/service/etc. and the updated data will be available to you.
Therefore, the following code is equivalent:
app.controller('myCtrl', function($scope, ngCart) {
$scope.names = [...];
...
console.log(ngCart.$cart);
});
A possible reason for the getting the error you got might be that, while editing the ngCart module, you had some sort of error (like a typo), which led to ngCart being invisible to angular.

Related

angular-ui: where is the page $scope inside a <script> element? For a google chart

I'm trying to add a chart to code created by others.
I understand a bit of angular, only...
I'm using angular-ui, so I don't have access to the HEAD tag where the simple Google instructions say to put the SCRIPT tags. I tried putting it later in the html, with other SCRIPT tags, but it kept saying "google" was undefined.
Finally, it seems to work if I put it inside the onload function:
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
drawCharts = function() {
var is = issue;
... create the chart using data inside $scope.issue
}
// google.charts.load( -- DOESN'T WORK HERE, google is undefined
$(window).load(function () {
// finally, in here, 'google' is defined
google.charts.load('current', {'packages': ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawCharts);
}
PROBLEM: drawCharts() needs to access the $scope, but here there's no access to $scope, so my angular data isn't accessible and drawCharts() fails.
So somewhere I need to connect
google.charts.setOnLoadCallback() and $scope
How?
I found one question where the person had a:
$rootScope
.$on('$viewcontentLoaded', function(...)
But he has it in main.js, and I don't have a main.js.
I tried putting it in my controller for the page, but it doesn't define $rootScope. I tried adding $rootScope to the parameters passed to the first line of my controller:
people.controller("voterIssueCtrl", function ($rootScope, $scope, $http, $cookieStore, $window, ClIENT
And that took care of the undefined $rootScope, but the $viewContentLoaded function was never called (it just contained a console.log() message...)
Perhaps my app.js is his main.js.
But it references the controller by name, so it probably loads it, so it probably can't reference something the controller defines.
Help?
===============
I pulled a google chart directive from the web
added the tag in index.html to pull it in
and added the directive to my module definition.
(Of course I forgot the 2nd one and the code didn't complain...)
Nothing. But no complaint that Google wasn't known...
Putting in sample data helps.
In the grand style of js and angular, it doesn't complain if the data isn't exactly in the form it needs...
If only Angular2 + Typescript had been invented sooner...

REST call on application init phase and defining constants based on REST call

I was wondering what the best moment is while initializing the app to retrieve data from:
1 - a REST service
2 - $routeParams
to define application wide constant.
config phase only accepts providers and during the config / run phase $routeParams properties are undefined.
This seems like somewhat in the right direction:
Can you pass parameters to an AngularJS controller on creation?
Also: how to define a constant within a controller, is that possible?
app.controller('MainCtrl', function($scope) {
//define app.constant here
}
--edit: typo
During run phase all the providers should be initialized and working correctly, you can use the $http service to retrieve what ever parameters are needed for you.
I am pretty sure the $routeParams are initialized at run phase as well.
Defining constants in a controller isn't a good practice (in my opinion), if they are unique to that controller then they are just variables, and if you want real application wide constants, use a service, that's what they are for :)
I know of one easy way to pass parameters to controllers on creation, which is using the angular ui router project: https://github.com/angular-ui/ui-router
In the resolve function you can do http calls if necessary, inject constants etc, it's very handy and personally I never build an angular project without it.
I am pretty sure there are more ways, but usually the best practice to pass data between controllers is using a service.
On a side note, if you have a piece of data that is common to more than 1 controller, the easiest way is to put that data on a service and do a watch on that service return value, for example, say I have isLoggedIn, which can change at any moment and a lot of controllers will want to be notified about it, use a UserService and watch for it's value:
UserService.isLoggedIn = function() {
return _isLoggedIn;
}
And in your Controller:
$scope.$watch(function() {
return UserService.isLoggedIn();
}, doSomeAction);
I hope this helps!
This http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/ seems like a nice guide, basically, you add the resolve to the state:
.state("customers", {
url : "/customers",
templateUrl: 'customers.html',
resolve: {
//any value you want, this function should return a promise,
//only when that promise is resolved, it will instantiate the controller
//Make sure however you add some signal that something is happening because
//while fetching it can seem like the page is not responding
customers: ['$http', 'anyOtherServiceYouMightNeed', function($http, otherService){
//return a promise
return $http.get('api/customers');
}],
//and for constant
constants: ['ConfigService', function(config) {
return config.appConstants;
}]
},
//customersCtrl will have customers resolved already
controller : 'customersCtrl'
});
app.controller('customersCtrl', ['$scope', 'customers', 'constants',
function($scope, customers, consts) {
//customers will be ready and resolved when the controller is instantiated
//you can do this with anything you might need inside a controller
}

Is it okay to use the scope of one controller from another using a service?

I was told if you need to share between controllers you should use a service. I have controller A, which is a list of news websites, and controller B which is a list of articles on the sites from controller A. Controller B contains the list of articles and an iframe to display the articles. But when you click on controller A it should fade out the iframe and fade in the list. In order to accomplish this I give Controller B's scope to a service that is injected into both controller A and controller B. My question is whether or not it's okay to do that.
Basically, I do this:
app.factory("sharedService", function () {
var $scope = null;
return {
SetScope: function (scope) {
$scope = scope;
},
ControllerB_Action: function () {
$scope.doSomething();
}
};
});
app.controller("controllerA", ["$scope", "sharedService", function ($scope, sharedService) {
$scope.onaction = function () {
sharedService.ControllerB_Action();
}
}]);
app.controller("controllerB", ["$scope", "sharedService", function ($scope, sharedService) {
sharedService.SetScope($scope);
}]);
I would say its not a good pattern, since basically, the $scope is an Object that represents your current view or DOM-State. A controllers (and/or Link-Functions of directives) are the Glue between this state and your Application-Logic - so in my opinion, the $scope-Object should always remain inside the Controllers/Links.
Therefore if you wanna share Data between 2 Controllers, you should extract what you wanna share inside the Service, but not put the whole scope there (since it has lots of additional information that you dont need and want inside both controllers).
What you can do is simply link the data you wanna share by reference - that way, your Service will also Sync the Data between the two Scopes.
There's probably a world of ways of doing this, but I'll tell you what I would do:
I'd make use of event emmiters.
Disclaimer: I haven't tested this code
Assuming that Controller B is nested in Controller A:
Controller A
var controllerBFunction_A;
$scope.$on('EventFromControllerB',function(data){
controllerBFunction_A = data.sharedFunctions.controllerBFunction_A;
});
Controller B
$scope.$emit('EvenFromControllerB',{
sharedFunctions: [
controllerBFunction_A,
controllerBFunction_B,
someOtherObject
]
});
I think this could work. In my opinion this has the benefit of selecting what you want to share between those controllers...but probably there's a more elegant way of doing this.

Angular.js - share the same model between multiple views by $rootScope [duplicate]

I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular some how and then resets the variable back to its initial value.
I assume this is not the correct way of declaring and initialising global variables, well its not really global, so my question is what is the correct way and is there any good examples around that work with the current version of angular?
You've got basically 2 options for "global" variables:
use a $rootScope http://docs.angularjs.org/api/ng.$rootScope
use a service http://docs.angularjs.org/guide/services
$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.
Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global' but you've got far better control over where those are used and exposed.
Using services is a bit more complex, but not that much, here is an example:
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
return {
name : 'anonymous'
};
});
and then in a controller:
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
}
Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/
If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:
var myApp = angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x');
Then use it in a controller like this:
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
}]);
The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax.
The other option is to use $rootScope, but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. It's advised to be used sparingly.
Since all scopes inherit from $rootScope, if you have a variable $rootScope.data and someone forgets that data is already defined and creates $scope.data in a local scope you will run into problems.
If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference":
myApp.value('clientId', { value: 'a12345654321x' });
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
this.change = function(value) {
clientId.value = 'something else';
}
}];
JSFiddle example
Example of AngularJS "global variables" using $rootScope:
Controller 1 sets the global variable:
function MyCtrl1($scope, $rootScope) {
$rootScope.name = 'anonymous';
}
Controller 2 reads the global variable:
function MyCtrl2($scope, $rootScope) {
$scope.name2 = $rootScope.name;
}
Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/
In the interest of adding another idea to the wiki pool, but what about AngularJS' value and constant modules? I'm only just starting to use them myself, but it sounds to me like these are probably the best options here.
Note: as of the time of writing, Angular 1.3.7 is the latest stable, I believe these were added in 1.2.0, haven't confirmed this with the changelog though.
Depending on how many you need to define, you might want to create a separate file for them. But I generally define these just before my app's .config() block for easy access. Because these are still effectively modules, you'll need to rely on dependency injection to use them, but they are considered "global" to your app module.
For example:
angular.module('myApp', [])
.value('debug', true)
.constant('ENVIRONMENT', 'development')
.config({...})
Then inside any controller:
angular.module('myApp')
.controller('MainCtrl', function(debug, ENVIRONMENT), {
// here you can access `debug` and `ENVIRONMENT` as straight variables
})
From the initial question is actually sounds like static properties are required here anyway, either as mutable (value) or final (constant). It's more my personal opinion than anything else, but I find placing runtime configuration items on the $rootScope gets too messy, too quickly.
// app.js or break it up into seperate files
// whatever structure is your flavor
angular.module('myApp', [])
.constant('CONFIG', {
'APP_NAME' : 'My Awesome App',
'APP_VERSION' : '0.0.0',
'GOOGLE_ANALYTICS_ID' : '',
'BASE_URL' : '',
'SYSTEM_LANGUAGE' : ''
})
.controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {
// If you wish to show the CONFIG vars in the console:
console.log(CONFIG);
// And your CONFIG vars in .constant will be passed to the HTML doc with this:
$scope.config = CONFIG;
}]);
In your HTML:
<span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>
localStorage.username = 'blah'
If you're guaranteed to be on a modern browser. Though know your values will all be turned into strings.
Also has the handy benefit of being cached between reloads.
Please correct me if I'm wrong, but when Angular 2.0 is released I do not believe$rootScope will be around. My conjecture is based on the fact that $scope is being removed as well. Obviously controllers, will still exist, just not in the ng-controller fashion.Think of injecting controllers into directives instead. As the release comes imminent, it will be best to use services as global variables if you want an easier time to switch from verison 1.X to 2.0.
You can also use the environment variable $window so that a global variable declare outside a controller can be checked inside a $watch
var initWatch = function($scope,$window){
$scope.$watch(function(scope) { return $window.globalVar },
function(newValue) {
$scope.updateDisplayedVar(newValue);
});
}
Becareful, the digest cycle is longer with these global values, so it is not always real-timed updated. I need to investigate on that digest time with this configuration.
I just found another method by mistake :
What I did was to declare a var db = null above app declaration and then modified it in the app.js then when I accessed it in the controller.js
I was able to access it without any problem.There might be some issues with this method which I'm not aware of but It's a good solution I guess.
Try this, you will not force to inject $rootScope in controller.
app.run(function($rootScope) {
$rootScope.Currency = 'USD';
});
You can only use it in run block because config block will not provide you to use service of $rootScope.
It's actually pretty easy. (If you're using Angular 2+ anyway.)
Simply add
declare var myGlobalVarName;
Somewhere in the top of your component file (such as after the "import" statements), and you'll be able to access "myGlobalVarName" anywhere inside your component.
You can also do something like this ..
function MyCtrl1($scope) {
$rootScope.$root.name = 'anonymous';
}
function MyCtrl2($scope) {
var name = $rootScope.$root.name;
}

Global variables in AngularJS

I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular some how and then resets the variable back to its initial value.
I assume this is not the correct way of declaring and initialising global variables, well its not really global, so my question is what is the correct way and is there any good examples around that work with the current version of angular?
You've got basically 2 options for "global" variables:
use a $rootScope http://docs.angularjs.org/api/ng.$rootScope
use a service http://docs.angularjs.org/guide/services
$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.
Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global' but you've got far better control over where those are used and exposed.
Using services is a bit more complex, but not that much, here is an example:
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
return {
name : 'anonymous'
};
});
and then in a controller:
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
}
Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/
If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:
var myApp = angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x');
Then use it in a controller like this:
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
}]);
The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax.
The other option is to use $rootScope, but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. It's advised to be used sparingly.
Since all scopes inherit from $rootScope, if you have a variable $rootScope.data and someone forgets that data is already defined and creates $scope.data in a local scope you will run into problems.
If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference":
myApp.value('clientId', { value: 'a12345654321x' });
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
this.change = function(value) {
clientId.value = 'something else';
}
}];
JSFiddle example
Example of AngularJS "global variables" using $rootScope:
Controller 1 sets the global variable:
function MyCtrl1($scope, $rootScope) {
$rootScope.name = 'anonymous';
}
Controller 2 reads the global variable:
function MyCtrl2($scope, $rootScope) {
$scope.name2 = $rootScope.name;
}
Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/
In the interest of adding another idea to the wiki pool, but what about AngularJS' value and constant modules? I'm only just starting to use them myself, but it sounds to me like these are probably the best options here.
Note: as of the time of writing, Angular 1.3.7 is the latest stable, I believe these were added in 1.2.0, haven't confirmed this with the changelog though.
Depending on how many you need to define, you might want to create a separate file for them. But I generally define these just before my app's .config() block for easy access. Because these are still effectively modules, you'll need to rely on dependency injection to use them, but they are considered "global" to your app module.
For example:
angular.module('myApp', [])
.value('debug', true)
.constant('ENVIRONMENT', 'development')
.config({...})
Then inside any controller:
angular.module('myApp')
.controller('MainCtrl', function(debug, ENVIRONMENT), {
// here you can access `debug` and `ENVIRONMENT` as straight variables
})
From the initial question is actually sounds like static properties are required here anyway, either as mutable (value) or final (constant). It's more my personal opinion than anything else, but I find placing runtime configuration items on the $rootScope gets too messy, too quickly.
// app.js or break it up into seperate files
// whatever structure is your flavor
angular.module('myApp', [])
.constant('CONFIG', {
'APP_NAME' : 'My Awesome App',
'APP_VERSION' : '0.0.0',
'GOOGLE_ANALYTICS_ID' : '',
'BASE_URL' : '',
'SYSTEM_LANGUAGE' : ''
})
.controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {
// If you wish to show the CONFIG vars in the console:
console.log(CONFIG);
// And your CONFIG vars in .constant will be passed to the HTML doc with this:
$scope.config = CONFIG;
}]);
In your HTML:
<span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>
localStorage.username = 'blah'
If you're guaranteed to be on a modern browser. Though know your values will all be turned into strings.
Also has the handy benefit of being cached between reloads.
Please correct me if I'm wrong, but when Angular 2.0 is released I do not believe$rootScope will be around. My conjecture is based on the fact that $scope is being removed as well. Obviously controllers, will still exist, just not in the ng-controller fashion.Think of injecting controllers into directives instead. As the release comes imminent, it will be best to use services as global variables if you want an easier time to switch from verison 1.X to 2.0.
You can also use the environment variable $window so that a global variable declare outside a controller can be checked inside a $watch
var initWatch = function($scope,$window){
$scope.$watch(function(scope) { return $window.globalVar },
function(newValue) {
$scope.updateDisplayedVar(newValue);
});
}
Becareful, the digest cycle is longer with these global values, so it is not always real-timed updated. I need to investigate on that digest time with this configuration.
I just found another method by mistake :
What I did was to declare a var db = null above app declaration and then modified it in the app.js then when I accessed it in the controller.js
I was able to access it without any problem.There might be some issues with this method which I'm not aware of but It's a good solution I guess.
Try this, you will not force to inject $rootScope in controller.
app.run(function($rootScope) {
$rootScope.Currency = 'USD';
});
You can only use it in run block because config block will not provide you to use service of $rootScope.
It's actually pretty easy. (If you're using Angular 2+ anyway.)
Simply add
declare var myGlobalVarName;
Somewhere in the top of your component file (such as after the "import" statements), and you'll be able to access "myGlobalVarName" anywhere inside your component.
You can also do something like this ..
function MyCtrl1($scope) {
$rootScope.$root.name = 'anonymous';
}
function MyCtrl2($scope) {
var name = $rootScope.$root.name;
}

Resources