In my angularJS app I use a directive. This directive needs to know the value of a variable in the application scope. Because the app scope variable needs to change when the directive updates it and the directive variable needs to change when the app scope variable changes, I used two way binding.
In my directive:
scope: {
"selectedObject": "=selectedobject"
}
In my html:
<dirname selectedobject="foo"/>
and in my controller:
$scope.foo = "somevalue";
//$scope.$apply(); Adding this, I get a '$digest already in progress' error
Now when I try to read the value of the selectedObject in my directive it starts with null instead of "somevalue". However, changes made in the directive scope propagate nicely to the application scope. How can I make sure it works the other way around too? That, if my controller changes the value of foo, this changes propagates to the directive scope?
Please read following article as I believe you fall into common pitfall and this article will help you understand your problem
http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/
Related
It is clear that a method should be set to scope in order to be visible or available for the view (in html) or in a directive or in any other place where the method should be accessed, so that the method can be accessed through the $scope. My question is to know whether $scope is always necessary or a good practice to use when a method is defined. For instance, following are different method declarations:
Scenario 1. $scope.myMethod = function(){};
Scenario 2. var myMethod= function(){};
if 'myMethod' is only used in one controller, is it required to set it to the $scope? What are the advantages or why scenario 1 or 2 is good ?
What if someone has declared it as $scope.myMethod = function(){} ? is it not good or an unnecessary load to the $scope ? What can be the best practice?
NB: I don't need to make any poll here, please let me know any pros and cons
You mainly use the first scenario for things like binding click events. If you will only call the myMethod you don't really need to define it in scope.
For example following will need the first definition:
<button ng-click="myMethod()">My Button</button>
But following can use the second:
angular.module('myCtrl', [])
.controller('myController', function($scope) {
var myMethod = function (text) {alert(text)};
$scope.mySecondMethod = function () { myMethod('second'); }
$scope.myThirdMethod = function () { myMethod('third'); }
In second case you can use mySecondMethod and myThirdMethod in event binding.
Scenario 1. $scope.myMethod = function(){};
Scenario 2. var myMethod= function(){};
Scope is the glue between the controller and the view. If you really
need any variable and methods for the current view, then this should
be added to the scope variable. Please see the controller as property
if you don't want to add the methods to scope.
Scenario 1
If you declare a method using the scope, then this will be available/accessed from the view.
Scenario 2
If you really don't need this method to be accessed from the view, then you can remove this method from the scope.
You need $scope to define a method only if you are calling that function from your html code.
You can use this or some_names also instead of $scope.
$scope is just to mean that the function's (mehtod's) scope is inside that controller function and can be accessible from the html code that written inside the controller
If the function is calling inside the javascript (controller) only, then use normal definition
function myMethod(){}
OR
var myMethod = function(){}
Declaring a method or variable as $scope variable is only for accessing from DOM. If you are creating a new variable in $scope. It just adding that variable to the clousure of $scope as $scope: {first, seccond, third}
When ever you are calling a $scope function that just returns from the closure. There is not much load to the $scope I guess
Scope is the glue between application controller and the view. During
the template linking phase the directives set up $watch expressions on
the scope. The $watch allows the directives to be notified of property
changes, which allows the directive to render the updated value to the
DOM.
Both controllers and directives have reference to the scope, but not
to each other. This arrangement isolates the controller from the
directive as well as from the DOM. This is an important point since it
makes the controllers view agnostic, which greatly improves the
testing story of the applications.
From the documentation
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'
});
Hello I have directive foo in which controller I have
$scope.valid = false
I am passing this variable inside another directive through isolated scoping in my template
<bar valid="valid">
and using an ng-if inside my template
<span ng-if="valid">Validated<span>
Now when I update valid in my child directive. It shows validated in my template. But the variable did not update in my parent directive controller. Why this is happening?
Note: In my child controller I am attaching the variable to controller instead of scope. Is this the reason it is behaving like this.
Indeed, if, in your child directive controller code, you write
function MyController($scope) {
this.valid = $scope.valid;
}
then setting the controller object's valid property is not going to change the $scope.valid, because you performed a copy of valid.
Instead, keep using $scope to pass the information about the change back up to the parent.
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.
I'm a bit confused with the use of $scope in controllers and of scope in directives. Please verify if my understanding is correct (and also provide some alternative ways how to do this).
Let's say I have an html:
<div ng-controller="app1_Ctrl">
.
.
.
<input type="text" ng-model="value"/>
<input type="checkbox" />
<button ng-click="submit()"></button>
</div>
And my main.js
(function() {
angular.module('mainApp', ['app1']);
})();
And my app1 looks like this (based on official AngularJS documentation here)
(function() {
var app = angular.module('app1', []);
app.controller('app1_Ctrl', ["$scope", function($scope) {
.
.
.
}]);
app.directive('app1_Dir1', [function() {
function link(scope, element, attr) {
scope.$watch(attr.someAttrOfCheckBox, function() {
// some logic here
});
function submit() {
// some logic here
}
}
return link;
}]);
})();
How does $scope.value passed in scope in directive so that I can do some manipulations there? Will ng-click fire the function submit() in the directive link? Is it correct to use scope.$watch to listen for an action (ticked or unticked of course) in checkbox element?
Many thanks to those who can explain.
By default, directive scope is controller $scope; but it means the directive is directly dependent on your controller and you need a different controller for each instance of the directive you want to use. It is usually considered a best practice to isolate your directive scope and specifically define the variables you wish to pass it from your controller.
For this, you will need to add a scope statement to your directive :
scope {
label :'#',
context : '=',
function : '&'
}
and update your view :
<my-directive label="labelFromController" context="ctxtFromController" function="myFunction()" ></my-directive>
The symbols denote the kind of thing you wish to pass through : # is for one-way binding (as a string in your directive), = is for two-way binding of an object (which enables the directive to update something in your controller), and & is for passing a function.
There are a lot of additional options and subtleties that are best explained by the Angular doc https://docs.angularjs.org/guide/directive. There are also some nice tutorials out there (e.g. http://www.sitepoint.com/practical-guide-angularjs-directives/)
Your submit() function is not attached to anything, so you won't be able to call if from your viewer. You need to define it as scope.submit = function() ... in your link function if you wish to access it.
You can use $watch for this kind of thing, but there are usually other more elegant ways to achieve this by leveraging the fact that angular already "watches" the variables it is aware of and monitors any changes he can (this can be an issue when some external service changes data for exemple, because angular cannot listen to events it is not made aware of). Here, you can probably simply associate the ng-model directive to your input checkbox to store its true/fale (checked/unchecked) value, and the ng-change or ng-click directives to act on it. The optimal solution will mostly depend on the exact nature of your business logic.
Some additional thoughts :
The HTML insides of your directive should be packaged in an inline template field, or in a separate HTML file referenced by the templateUrl field in your directive.
In your HTML code above, your directive is not referenced anywhere. It should be an element, attribute or class (and your directive definition should reflect the way it can be called, with the restrict field). Maybe you have omitted the line containing the directive HTML, but as it stands, your directive doesn't do anything.
To my knowledge, you don't need to return link. Think of it as the "body" of your directive, where you define the variables and functions you will call in the HTML.
Your directive doesn't actually need HTML code and the above thoughts might be irrelevant if you are going in a different direction, but encapsulating some kind of view behaviour that you want to reuse is probably the most common use of directives.