Related Post, but didn't help:
Scoping issue when setting ngModel from a directive
EDIT: Can I use ng-model with isolated scope? didn't work either.
I got the some problem but in a more complex way I guess. I want to write a pulldown that does not use any input for data saving. I'd rather have the ngModel to take care of it.
http://jsfiddle.net/QeM6g/6/
The jsFiddle example above shows a demo where the above described methods didn't work.
// this is what should work but doesn't
ngModel.$setViewValue(value);
scope.$apply(attr.ngModel,value);
For some reason the scope of the ngModelController is a sibling of my scope. so it doesn't pass the changes back to the parent. at least all other sibling scopes behave as you'd expect. i.e. ng-change works in combination.
Angularjs doesn't deal very well with direct bindings to primitive types.
If you change this line:
$scope.productId = 16;
to something like this:
$scope.selectedProduct = {
id: 16
}
and change those references on the rest of the code, you should be able to overcome the issue.
jsFiddle: http://jsfiddle.net/M2cL7/
Don't bind to primitives in a scope, bind to an object in the scope.
From https://github.com/angular/angular.js/wiki/Understanding-Scopes
... until you try 2-way data binding
(i.e., form elements, ng-model) to a primitive (e.g., number, string,
boolean) defined on the parent scope from inside the child scope. It
doesn't work the way most people expect it should work. What happens
is that the child scope gets its own property that hides/shadows the
parent property of the same name. This is not something AngularJS is
doing – this is how JavaScript prototypal inheritance works. New
AngularJS developers often do not realize that ng-repeat, ng-switch,
ng-view and ng-include all create new child scopes, so the problem
often shows up when these directives are involved.
This issue with primitives can be easily avoided by following the
"best practice" of always have a '.' in your ng-models
so
<input ng-model="tweetText">
becomes
<input ng-model="tweet.text">
A great summary is here:
https://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m
Related
If you have a controller what is the preferred method for data binding, multiple smaller ones or one big object e.g.:
$scope.username = 'John Doe';
$scope.email = 'me#me.com';
$scope.city = 'Amsterdam';
or
var user = {};
user.username = 'John Doe';
user.email = 'me#me.com';
user.city = 'Amsterdam';
$scope.user = user;
I would go with second one, from angularjs wiki
Scope inheritance is normally straightforward, and you often don't
even need to know it is happening... until you try 2-way data binding
(i.e., form elements, ng-model) to a primitive (e.g., number, string,
boolean) defined on the parent scope from inside the child scope. It
doesn't work the way most people expect it should work. What happens
is that the child scope gets its own property that hides/shadows the
parent property of the same name. This is not something AngularJS is
doing – this is how JavaScript prototypal inheritance works. New
AngularJS developers often do not realize that ng-repeat, ng-switch,
ng-view and ng-include all create new child scopes, so the problem
often shows up when these directives are involved. (See this example
for a quick illustration of the problem.)
This issue with primitives can be easily avoided by following the
"best practice" of always have a '.' in your ng-models – watch 3
minutes worth. Misko demonstrates the primitive binding issue with
ng-switch.
Having a '.' in your models will ensure that prototypal inheritance is
in play. So, use
<input type="text" ng-model="someObj.prop1"> rather than
<input type="text" ng-model="prop1">.
If you really want/need to use a primitive, there are two workarounds:
Use $parent.parentScopeProperty in the child scope. This will prevent
the child scope from creating its own property. Define a function on
the parent scope, and call it from the child, passing the primitive
value up to the parent (not always possible)
https://github.com/angular/angular.js/wiki/Understanding-Scopes
Preface
When I declare a directive under a controller, e.g.
<div ng-controller="MyController">
<my-directive></my-directive>
</div>
the directive inherits that controller's scope by default. This means if the controller defines
$scope.Heaven = "Free Beer"
then I have access to that within the directive's template via
{{ Heaven }}
Question
When declaring a directive within another directive, why doesn't the child inherit scope like it would if placed in a controller?
<my-parent-directive>
<my-child-directive>
</my-child-directive>
</my-parent-directive>
In short, if I declare a controller function for my-parent-directive and in it write:
$scope.Heaven = "Free Beer"
My child directive doesn't have access to this by default. Why is that?
(This assumes "scope: true" within the parent, no scope declaration in the child, and the child requiring the parent via "require: 'my-parent-directive')
Example codepens:
Directive wrapped in controller
Directive wrapped in directive
Question was modified after answer was given - the below is to preserve the reference
Directive wrapped in directive old
I am looking at the "Directive wrapped in directive old" on codepen. I think it is this you want to fix, but I'm not certain since your codepen is different to the example in your question (that's not a criticism, just clarification in case I am heading down the wrong route for you!)
However, if I am correct (and I am referring to the "Directive wrapped in directive old" on codepen for the rest of this answer):
You have declared the scope in myWrapper to be inherited ("scope: true"), therefore any properties that you add to the scope within myWrapper (such as "$scope.passdown = $attrs.passdown;") will only be visible to myWrapper.
You can remove the "scope: true" from myWrapper to share the scope between everything (not a great structure to use, but it will work) and you will solve your immediate problem, if I have understood you correctly. Or you can move the "passdown" property to a mutable object on the "parent" controller "$scope.abc = {passdown: ''};" for example. Then modify the value in myWrapper: "$scope.abc.passdown = $attrs.passdown;" and access it as "abc.passdown" in your interpolated expressions.
a bit of background:
changes to immutable types in "child" controllers/directive will make a copy of the property and those changes will never be seen on any other scope.
No scope declaration means shared scope - all components that share this scope too can see any properties / changes (to mutables) made on the scope. Tends to end up with closely coupled components that become very difficult to maintain.
"scope: true" means inherited scope and any additions made to the scope will only be visible to the inherting scope (ie the "child"). Changes to mutable properties in the parent will be visible to all other components that share this scope.
"scope: {...}" creates an isolated scope and provides a safe way to expose properties to parents and let the children modify those properties. This implementation is more work but you will end up with code that is easier to understand, maintain and share.
I hope this answer isn't too rambling and it helps you solve your problem.
I 'm trying to write a collapsible, reusable calculator directive, that binds to an input field (in the parent scope). This input field itself has a ngModel binding.
When the user presses the equals-button of my directive this parent scope model should be updated. I need to isolate the scope so I can reuse it:
Here is the simplified code and how I would like to use it:
http://plnkr.co/edit/OSOcxydJWh8K520nstAU?p=preview
I tried passing in the values as an attribute. but that does not work because I don't know how to update this attribute inside of the controller(I tried the $attrs service).
So how can I update the model from the directive?
Maybe you're overthinking it, maybe I'm underthinking it. Either way, here's all I did to change yours to make it work:
if ($scope.operator ==='+') {
$scope.field = parseInt($scope.field) + $scope.operand;
}
I uncommented your scope and then I made sure that your controller made reference to the data you had exposed in your scope. That's it.
And here's a working version of your Plunker: http://plnkr.co/edit/btBi3E
You need to use ngModelController. Here's a link with docs, with a handy example:
NgModelController
In the video AngularJS MTV Meetup: Best Practices (2012/12/11), Miško explains "..if you use ng-model there has to be a dot somewhere. If you don't have a dot, you're doing it wrong.."
However, the very first example (The Basics) in the Angular.JS website seems to contradict it. What gives? Has Angular.JS changed since the MTV meetup that it's now more forgiving with ng-model?
That little dot is very important when dealing with the complexities of scope inheritance.
The egghead.io video "The Dot" has a really good overview, as does this very popular stack overflow question: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
I'll try to summarize it here:
Angular.js uses scope inheriting to allow a child scope (such as a child controller) to see the properties of the parent scope. So, let's say you had a setup like:
<div ng-controller="ParentCtrl">
<input type="text" ng-model="foo"/>
<div ng-controller="ChildCtrl">
<input type="text" ng-model="foo"/>
</div>
</div>
(Play along on a JSFiddle)
At first, if you started the app, and typed into the parent input, the child would update to reflect it.
However, if you edit the child scope, the connection to the parent is now broken, and the two no longer sync up. On the other hand, if you use ng-model="baz.bar", then the link will remain.
The reason this happens is because the child scope uses prototypical inheritance to look up the value, so as long as it never gets set on the child, then it will defer to the parent scope. But, once it's set, it no longer looks up the parent.
When you use an object (baz) instead, nothing ever gets set on the child scope, and the inheritance remains.
For more in-depth details, check out the StackOverflow answer
Dot will be required when you prototypically inherit one scope from another for example in case of ng-repeat a new scope is created for every line item which prototypically inherits from parent scope. In the basic example there is no prototype inheritance since there is only one scope but if you have a number of child scopes then you will start facing the problem. The link below will make everything clear.
https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-repeat
So to solve this, make sure in the JS you declare the parent first:
e.g.
$scope.parent
followed by:
$scope.parent.child = "Imma child";
doing just the child without the parent will break Angular.
According to #OverZealous's answer, I thought up a dirty but comfortably simple and quick workaround for this:
$scope.$s = $scope
$scope.foo = 'hello'
Then use $s in template can safely modify model:
<input ng-model="$s.foo"/>
I wrote a service for such dirty works in my project.
To get a grip on AngularJS I decided to play around with one of the examples, specifically, simply adding a "complete" screen to the Todo-example, when the user has entered 5 todos it uses a switch-case to switch to another div. Code is available here http://jsfiddle.net/FWCHU/1/ if it's of any use.
However, it appears that each switch-case gets its own scope ($scope.todoText is not available), however it can be accessed using "this" from within addTodo() in this case. So far so good, but say I want to access todoText (which is inside the switch-case) outside of the switch-case, how would I go about doing that? Can I bind the switch-case scope to the model perhaps, is it accessible in some other way or should this be solved in some other way?
PS. I'm not trying to find ANY solution to the code above, I'm pretty sure I know how to solve it without using switch-cases, I want to understand how scopes work in this case!
Mark has some great suggestions! Make sure you also check out the AngularJS Batarang Chrome Extension to see the various scopes and their values (among other things). Note it doesn't appear to work well with jsFiddle.
I'm not sure how to access inner scopes directly but here is one way to access the same text in the outer scope by binding to an object instead of a primitive.
1) Declare todoText as an object instead of a primitive in your controller:
$scope.todoText = {text: ''};
2) Bind to todoText.text instead of just todoText:
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText.text" size="30" placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
3) Modify the existing functions to use todoText.text:
$scope.addTodo = function() {
$scope.todos.push({text:$scope.todoText.text, done:false, width: Math.floor(Math.random() * 100) + 50});
$scope.todoText.text = '';
};
Take a look at this fiddle and note that the text displayed beneath the textbox when you type something in is accessing the todoText.text on the outside scope.
If you change the code back to use a primitive (like in this fiddle) the parent scope todoText won't reflect any changes you make to the textbox. This is likely more to do with how JavaScript copies reference values (see this post for more info) and less an AngularJS specific thing.
Update2: Now that I know a little more about AngularJS, here's a much better answer.
say I want to access todoText (which is inside the switch-case)
outside of the switch-case, how would I go about doing that?
There is no way for parent scopes to access child scopes. (One reason for this restriction, according to Angular developers, is for easier memory management of scopes.) (Well, you could use $$childHead and $$childTail to access child scope, but you shouldn't!)
Can I bind the switch-case scope to the model perhaps, is it
accessible in some other way or should this be solved in some other
way?
There are three common ways to access the parent model from the child scope:
Do what #Gloopy suggests: create an object in the parent scope, then refer to properties on that object in the child scope.
Use $parent in the child scope to access the parent scope and its properties, even primitive properties.
Call a method on the parent scope
To convert your fiddle to use $parent:
<input type="text" ng-model="$parent.todoText" ...
$scope.addTodo = function() {
$scope.todos.push({text: $scope.todoText, ...
$scope.todoText = '';
As I mentioned in the comments on Gloopy's answer, ng-repeat and ng-switch both have the new child scope prototypically inherit from the parent scope. ng-repeat also copies the loop variable/item to the new child scope (and the nuances that #Gloopy describes with primitives vs object applies). ng-switch does not copy anything from the parent scope.
To see what the inner/child scope looks like, add the following after the ng-switch-when:
<a ng-click="showScope($event)">show scope</a>
and add this to your controller:
$scope.showScope = function(e) {
console.log(angular.element(e.srcElement).scope());
}
Update1: (strikethroughs added to bad advice, []'s added for clarity)
For this scenario, where AngularJS is creating additional inner scopes (implicitly), and you don't really want/need another controller, I like Gloopy's solution. A service (what I originally suggested below) is [the wrong way to do this] probably overkill here. I also like that Gloopy's solution does not require the use of 'this' in the controller methods.
Original Answer: (strikethroughs added to bad advice, []'s added for clarity)
To see where scopes are being created (if you haven't tried this already, it is handy):
.ng-scope { margin: 4px; border: 1px dashed red }
To access todoText outside the switch-case (hence outside of its scope), you're essentially asking about inter-controller communication, since multiple scopes are involved. You have a few options, but a service is probably best. Store the data (that needs to be shared) inside the service, and inject that service into each controller that needs access to the data.
For your specific example, I think you'd need to attach a controller to each switch-case and inject the service into it, to get access to the shared data.
See also AngularJS: How can I pass variables between controllers?.
The other options:
Using $scope.$parent in the inner scope is [one way to do this -- see Update2 above] not recommended, since then a controller would be making assumptions about how the data is presented.
Using $rootScope is not recommended, except maybe for simple, one-off applications. That shared data may start to take on a life of its own, and $rootScope is not the place for that to happen. Services are easier to reuse, to add behavior to, etc.
Using $scope.$emit is another option, but it seems messy and a bit odd: emitting events to share data (instead of triggering behavior).
[Using an object in the parent scope is probably best -- see #Gloopy's answer.]