When I try to call one controller method from another controller in the angular javascript, an error occurs. I think something is missing there. If anyone has the complete method to do this, please give me the answer.
Being able to share a variables throught different controllers it's a common issue in angular.
Your function can be seen as an object: you'll need to share it's reference throught scopes.
To perform that, you can either:
.
Use a service:
You can see services as singletons object that are injected in your controllers: a common object shared throught your controllers.
You can use this wonderful guide to understand how to share your scope variables by using services (this guide uses factory and not services, but for your needs will be ok).
If you still wants to use services, follow this answer.
.
Use scope hierarchy:
Sometimes you have a hierarchy between controllers (and thus, scopes).
Let's assume you have an HTML formatted this way:
<div ng-controller="parentController">
<!-- some content here...-->
<div ng-controller="childController">
<!-- some content here...-->
</div>
</div>
This structure will produces two different scopes: one for parentController, and one for childController.
So, you childController scope will be able to access parentController scope by simply using $parent object. For example:
myApp.controller('parentController', function($scope) {
$scope.functionExample = function(){
console.log('hey there');
};
})
myApp.controller('childController', function($scope) {
$scope.functionExample();
});
Note: the parent object is accesible directly in your child scope, even if declared in your parent.
But beware of this method: you can't never really sure of your scope hierarchy, so a check if the variable is defined should be always needed.
.
Use $rootScope:
You can use rootscope as a common shared object to share yours. But beware: this way, you'll risk to pollute your $rootScope of variables when $rootScope should be used for other uses (see message broadcasting).
Anyway, see this answer for an example use case.
.
Use Messages:
By using messages, you can share objects references, as shown in this example:
myApp.controller('parentController', function($scope, $rootScope) {
var object = { test: 'test'}
$rootScope.$broadcast('message', message)
console.log('broadcasting');
});
myApp.controller('childController', function($scope, $rootScope) {
$scope.$on('message', function(message){
console.log(message);
});
});
.
In the end, i suggest you to use a common service for all your variables or, where you can, use the scope hierarchy method.
If two controllers are nested in one controller,
then you can simply call the other by using:
$scope.parentMethod();
Angular will search for parentMethod() function starting with the current scope up to it reach the $rootscope
Related
I created a directive, I´m using in my template:
<data-input> </data-input>
In my directive (dataInput) I have the template (...data-input.html).
In that template the html-code says:
<input ng-change="dataChanged()" ... > ...
In the JavaScript it says:
scope.dataChanged= function(){ //change the data }
Works perfectly, but know I need to safe the changed data to a variable in my controller (that has a different scope of course).
The template, where I put the <data-input> </data-input> belongs to the final scope, I´m trying to reach.
I tried it via parameter, but it didnt work.
Thanks
Here are your options:
You can nest controllers if possible. This will create scope inheritance and you will be able to share variables of the parent.
You can use $rootscope from both the controllers to share data. Your dataChanged function can save anything to the $rootscope
You can use angular.element to get the scope of any element. angular.element('data-input').scope() returns it's cope.
This is not recommended. But there are circumstances in which people use global space to communicate between angular and non-angular code. But I don't think this is your case.
You can use Angular Watches to see changes is some variable, like this
eg:
$scope.$watch('age + name', function () {
//called when variables 'name' or 'age' changed
//Or you can use just 'age'
});
I'm wondering why i should use isolated scope directives? I can always get some data with service inside my controller and those data will be available inside directive that don't have isolated scope, if i want to use that directive in other place, i can just send request and get the data.... Right?
When you create directive with isolated scope, you must get the data and pass it to directive..
What is the advantage of using isolated scope directives?
Why i should use it and when?*
Because it makes your directive an own module(design-wise, Im not talking about angular.modules ;-) with a clear defined self-contained interface, which means that it is reusable in any context. It also makes its code readable, as everything that the directive works with is in the directives code and not in some magic parent scope that it relies on. Lets look at an example without an isolated scope:
Controller:
angular.module("carShop",[])
.controller("CarStorefrontController",function(){
//For simplicity
this.cars = [
{ name: 'BMW X6', color: 'white' },
{ name: 'Audi A6', color: 'black' }
];
});
Directive:
angular.module("carShop")
.directive("carList",function(){
return {
template: ['<ul>',
'<li ng-repeat="car in vm.cars">',
'A {{car.name}} in shiny-{{car.color}}',
'</li>',
'</ul>'].join("")
};
});
Page:
<div ng-app="carShop" ng-controller="CarStorefrontController as vm">
<h2>Welcome to AwesomeCarShop Ltd. !</h2>
<p>Have a look at our currently offered cars:</p>
<car-list></car-list>
</div>
This works, but is not reusable. If I want to display a list of cars somewhere else in my application, I need to rename my controller there to vm and have it have a field named cars containing my array of cars for it to work. But if I change my directive to
angular.module("carShop")
.directive("carList",function(){
return {
scope: { cars: '=' },
template: [ /* same as above */ ].join("")
};
});
and change <car-list></car-list> on my storefront page to <car-list cars="vm.cars"></car-list>", I can reuse that directive everywhere by just passing in any array of cars without caring where that array came from. Addiionally, I can now replace my Controller on the storefront page with a completely different one, without having to change my directive definition(and without changing all the other places where I use car-list).
It really comes down to the same reason why you should not put all your javascript variables into one global scope so they are easily accessible from everywhere: reusability, readability, maintainability - that is what you get by modularizing and encapsulating your code, by going for low coupling and high cohesion following the black-box-principle.
Directive with isolated scope basically used when you want to create a component that can be reusable throughout your app, so that you can use it anywhere on you angular module.
Isolated scope means that you are creating a new scope which would not be prototypically inherited from the parent scope. But you could pass values to directive that you want to required from the parent scope. They can be pass in the various form through the attribute value, there is option that you can use scope: {} to make directive as isolated scope.
# - Means interpolation values like {{somevalue}}
= - Means two way binding with parent scope variable mentioned in
attribute {{somevalue}}
& - Means you can pass method reference to directive that can be call from the directive
Isolated scope created by using $scope.$new(true); where $scope is current scope where the directive tag is placed.
As your saying, you are going to store data in Service, rather than make an isolated scope. But this approach never going to work for you as service is singleton thing which is having only one instance. If you want to use your directive multiple times then you need to make another variable in service that would take the data required for other element. If that directive count increased to 10, then think how you service will look like, that will look really pathetic.
By using isolated scope, code will look more modularize, code re-usability will be improved. Isolated scope variables never going to conflict with the other variables which is of same name in parent scope.
When creating an Angular Module one could essentially add global arrays or objects to the module. Like so..
var myApp = angular.module('myApp', ['myModule']);
myApp.run(function()
{
});
angular.module('myModule', [])
.run(function()
{
// global to module
var thisModule = angular.module('myModule');
thisModule.globalArray = [];
thisModule.globalObject = {};
});
So here's the question(s). Would it be a bad idea to do something like this? Is there anything in the documentation that recommends not doing this? And if so, why would or wouldn't you recommend not doing this?
Demo:
http://jsfiddle.net/hrpvkmaj/8/
In general, Angular goes to great lengths to avoid global state. You can observe this in the dependency injection system that the framework is based on. To use a component, you must inject it as a parameter that is wired up behind the scenes. The framework also has a powerful scoping system that allows for nice and easy encapsulation. Relying on global variables works against these systems.
In particular, it would be a bad idea to do something exactly like your code example because it isn't how Angular was designed to be used. You shouldn't be adding your own properties to Angular's module object. At the very least, you should be injecting the $rootScope object and adding your global variables to that.
app.run(function($rootScope)
{
$rootScope.globalArray = [];
$rootScope.globalObject = {};
});
From the Angular documentation:
Every application has a single root scope. All other scopes are descendant scopes of the root scope.
If you went this route, you could inject $rootScope wherever you need to use those global values.
However, the Angular team discourages using $rootScope.
Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.
There is another way of defining global values in Angular that is even preferable over using $rootScope: defining a value provider.
A value provider is the simplest kind of provider. It defines a single value that can be injected throughout your app.
You can define one like this:
app.value("myValue", {
someProp: 'Hello World'
});
Then you can inject the value wherever you need it like this:
app.controller("myController", function ($scope, myValue) {
$scope.someValue = myValue.someProp;
});
Here's a fiddle using a value provider to inject a global value.
In the end, any answer you get, including this one, will include some level of subjectivity. There are many ways to handle global values, but Angular provides some really convenient ways of using the framework to accomplish this.
A few questions regarding structuring Angular code and the behavior of JavaScript when using variable bound vs private method naming function conventions. Is there a performance or stylistic reason for using variable bound functions / first class functions in AngularJS over private method naming? How is hoisting affected in each method? Would the second method below reduce the amount of hoisting performed and would this have a noticeable affect on application performance?
An example of private method naming. Is this a recommended way to structure Angular code?
(function () {
'use strict'
function modalController(dataItemsService, $scope) {
var vm = this;
function _getSelectedItems() {
return dataItemsService.SelectedItems();
}
function _deleteSelectedItems() {
dataItemService.DeleteItem();
$("#existConfirmDialog").modal('hide');
}
vm.SelectedItems = _getSelectedItems;
vm.deleteItemRecord = _deleteItemRecord;
}
angular.module('app').controller('modalController', ['dataItemService', '$scope', modalController]
})();
An example of variable bound functions. What about this method of structuring angular code within the controller - is there any disadvantage or advantage in terms of performance/style?
angular.module('appname').controller("NameCtrl", ["$scope", "$log", "$window", "$http", "$timeout", "SomeService",
function ($scope, $log, $window, $http, $timeout, TabService) {
//your controller code
$scope.tab = 0;
$scope.changeTab = function(newTab){
$scope.tab = newTab;
};
$scope.isActiveTab = function(tab){
return $scope.tab === tab;
};
}
]);
The first method, using "private" methods and exposing them via public aliases, is referred to as the Revealing Module Pattern, although in the example the methods aren't actually private.
The latter is a pretty standard Constructor Pattern, using $scope as context.
Is there a performance or stylistic reason for using variable bound functions / first class functions in AngularJS over private method naming?
Is [there] a recommended way to structure Angular code?
TL;DR
Fundamentally, there isn't much difference between the two styles
above. One uses $scope, the other this. One Constructor function is defined in a closure, one is defined inline.
There are scenarios where you may want a private method or value.
There are also stylistic and (probably insignificant) performance
reasons for using the variable this/vm over $scope. These are not mutually exclusive.
You'll probably want to use a
basic, bare bones, old school Constructor Pattern, and a lot of
people are exposing state and behavior via this instead of $scope.
You can allow yourself data privacy in the Controller, but most of
the time this should be leveraged by a Service/Factory. The main exception is data representative of the state of the View.
Don't use jQuery in your Controller, please.
References:
AngularJS Style Guide by Todd Motto.
AngularJS Up & Running
To answer your question thoroughly, I think it important to understand the responsibility of the Controller. Every controller's job is to expose a strict set of state and behavior to a View. Put simply, only assign to this or $scope the things you don't mind your user seeing or playing with in your View.
The variable in question (vm, $scope) is the context (this) of the instance being created by the Controller function.
$scope is Angular's "special" context; it has some behaviors already defined on it for you to use (e.g. $scope.$watch). $scopes also follow an inheritance chain, i.e. a $scope inherits the state and behaviors assigned to its parent $scope.
Take these two controllers:
angular.module("Module")
.controller("Controller", ["$scope", function($scope) {
$scope.tab = 0;
$scope.incrementTab = function() {
$scope.tab++;
};
}])
.controller("OtherController", ["$scope", function($scope) {
// nothing
}]);
And a view
<div ng-controller="Controller">
<p>{{ tab }}</p>
<button ng-click="incrementTab();">Increment</button>
<div ng-controller="OtherController">
<p>{{ tab }}</p>
<button ng-click="incrementTab();">Increment</button>
</div>
</div>
Example here
What you'll notice is that even though we didn't define $scope.tab in OtherController, it inherits it from Controller because Controller is it's parent in the DOM. In both places where tab is displayed, you should see "0". This may be the "hoisting" you're referring to, although that is an entirely different concept.
What's going to happen when you click on the first button? In both places we've exposed "tab", they will now display "1". Both will also update and increment when you press the second button.
Of course, I may very well not want my child tab to be the same tab value as the parent. If you change OtherController to this:
.controller("OtherController", ["$scope", function($scope) {
$scope.tab = 42;
}]);
You'll notice that this behavior has changed - the values for tab are no longer in sync.
But now it's confusing: I have two things called "tab" that aren't the same. Someone else may write some code later down the line using "tab" and break my code inadvertently.
We used to resolve this by using a namespace on the $scope, e.g. $scope.vm and assign everything to the namespace: $scope.vm.tab = 0;
<div ng-controller="OtherController">
<p>{{ vm.tab }}</p>
<button ng-click="vm.incrementTab();">Increment</button>
</div>
Another approach is to use the simplicity and brevity of this and take advantage of the controllerAs syntax.
.controller("OtherController", function() {
this.tab = 0;
});
<div ng-controller="OtherController as oc">
<p>{{ oc.tab }}</p>
</div>
This may be more comfortable for people who are used to using plain JS, and it's also easier to avoid conflicts with other Angular sources this way. You can always change the namespace on the fly. It's also a bit "lighter" on performance since you're not creating a new $scope instance, but I'm not sure there's much gain.
In order to achieve privacy, I would recommend encapsulating your data in a Service or Factory. Remember, Controllers aren't always singletons; there is a 1:1 relationship between a View and a Controller and you may instantiate the same controller more than once! Factories and Service objects are, however, singletons. They're really good at storing shared data.
Let all Controllers get a copy of the state from the singleton, and make sure all Controllers are modifying the singleton state using behaviors defined on the Service/Factory.
function modalController(dataItemsService) {
var vm = this;
vm.selectedItems = dataItemsService.SelectedItems(); // get a copy of my data
vm.updateItem = dataItemService.UpdateItem; // update the source
}
But wait, how do I know when another part of my app has changed my private data? How do I know when to get a new copy of SelectedItems? This is where $scope.$watch comes into play:
function modalController(dataItemsService, $scope) {
var vm = this;
vm.updateItem = dataItemService.UpdateItem; // update the source
// periodically check the selectedItems and get a fresh copy.
$scope.$watch(dataItemsService.SelectedItems, function(items) {
vm.items = items;
});
// thanks $scope!
}
If your data is not shared, or if your private data is representative of the View layer and not the Model layer, then it's totally OK to keep that in the controller.
function Controller() {
var buttonClicked = false;
this.click = function() {
buttonClicked = true; // User can not lie and say they didn't.
};
}
Lastly, DO NOT USE JQUERY IN YOUR CONTROLLER, as your reference did!
$("#existConfirmDialog").modal('hide');
This example might not be purely evil, but avoid accessing and modifying the DOM outside a Directive, you don't want to break other parts of your app by modifying the DOM underneath it.
I need an object to be globally accessible all throughout my Angular application, and I've gladly put this object in a value service.
Unfortunately, this object is computed by another service, and I've not been able to inject myService into same value service.
ATM, I've acheived my goal with something like this:
global service code
app.service('myService', function() {
this.foo = function() {
// some code that returns an object
return computedObject
}
})
app.run(function ($rootScope, myService) {
$rootScope.global = {dbObject: myService.foo()}
})
And which I can use in any controller that pleases me by simply injecting $rootScope in it
However, I don't like the need of injecting the whole $rootScope wherever I need that damn object, and I trust is not much safe (or efficient?) either, since the team specifies
Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.
Conversely, don't create a service whose only purpose in life is to store and return bits of data.
Do you, perchance, happens to know any way I can inject a service into a service value?
Or maybe any other Angular best practice which I could exploit?
I forgot one very important notice
The computation of the object could be quite computational intense, so I absolutely don't want it to be recomputed everytime I move from page to page, or anything else really.
Ideally Using $rootScope for storing a few globally required values is totally ok. But if you are still adamant on using a module, I suggest you use a provider.
Make your 'myService' a provider and that will let you configure the variables in the service.
More info here
AngularJS: Service vs provider vs factory
You could use $broadcast to send the value from the value service to myService.
You would still need to inject $rootscope into each of the services, but from then on you could just inject myService around the rest of the app.
Reference here.
I need an object to be globally accessible all throughout my Angular application
I would use service. Since Service is singleton you can register the service to all your controllers and share any data over service.
Unfortunately, this object is computed by another service, and I've not been able to inject myService into same value service.
Just create one main service (Parent) and child service that will inherit the parent. (like abstract service in Java world).
Application.factory('AbstractObject', [function () {
var AbstractObject = Class.extend({
virtualMethod: function() {
alert("Hello world");
},
abstractMethod: function() { // You may omit abstract definitions, but they make your interface more readable
throw new Error("Pure abstract call");
}
});
return AbstractObject; // You return class definition instead of it's instance
}]);
Application.factory('DerivedObject', ['AbstractObject', function (AbstractObject) {
var DerivedObject = AbstractObject.extend({
virtualMethod: function() { // Shows two alerts: `Hey!` and `Hello world`
alert("Hey!");
this._super();
},
abstractMethod: function() {
alert("Now I'm not abstract");
}
});
return DerivedObject;
}]);
Now, we can add some logic into AbstractObject and continue use DerivedObject
Here is example Plunker