ng-repeat scope not available to a directive within it - angularjs

I have a directive that is repeated by an ng-repeat.
<div ng-repeat="p in people">
<p>{{p.name.first}}</p>
<slider-box
title-text="{{p.name.first}}"
body-text="Some body text"
img-src="{{p.photo}}"
more-link="#"></slider-box>
</div>
</div>
If I put a <p>{{p.name.first}}</p> before the directive, the p shows off a first name, but the slider-box doesn't seem to have access to p and therefore comes up blank as there's no data being given to it.
It probably isn't an async issue, as there are boxes being created, so angular knows that there is something to ng-repeat , and the <p> is getting filled in.
I've made an an example site here that shows an example of the directive with dummy data (just strings) and then the repeated ones are below that.
A very similar question has been asked here but no code examples were posted and the trail seems to have gone dead.

You should pass the attributes into the scope directly in the directive declaration.
In your directive declaration, instead of just having scope: {} , have something like scope:{ imgSrc:"#" }. It will pass the value of the attribute directly inside the isolated scope of your directive.
Take a look at this short tutorial for a better explanation.

Related

Function never called in an AngularJS directive controller

I am facing a strange situation in which I have created a directive, to which a controller is attached, and one of the two tiny functions of the controller is never called from the view whereas the other function is.
Here is the plunker.
The message I expect is (bold is what does not show up)
You are limited to: Prison
I have already created tens of directives, whether in their own right or as wrappers around existing directives available on GitHub, from lightweight ones such as custom-select to behemoths such as angular-ui-grid.
I am at the end of my wits here as to why {{getArea()}} produces no text at all in the view. I've scrutinized the code, trying to do it with new eyes, so to speak, and I see nothing wrong. I've created a specific project in Eclipse for this tiny piece of code, installed Wampserver just so I could set breakpoints in Firebug and God knows to what great lengths I had to go just so that I could understand what is wrong with the code I wrote.
For instance, in isRestricted(), I can call getArea() without any problem. However, Angular seems to not find the function from the directive.
A few similar questions have already been asked but none of the errors (missing controller or ng-app specification, missing dependency list at module declaration, nested controllers, etc.) seem to apply. There's obviously an important lesson to be learned here and I'm truly eager to learn it.
EDIT: The lesson learned is that ng-if creates a new scope. That new scope comes in between the controller and the directive, which leads to the template of the directive losing access to anything defined in the controller (at least, that's how I would phrase it). (Note that a comment hinted at directive priority.)
There are several solutions, which all maintain the prototypical inheritance needed for the template to access the functions defined in the controller:
not using an isolate scope
not defining the ng-if directive on the top-level element of my directive, as that causes a conflict (between my controller's scope and the scope defined by ng-if). I believe ng-if wins here, which leads to the controller's scope being out of reach of the directive. Using ng-if on a child div does the trick (because then, the ng-if scope inherits my controller's scope, hence making the functions available to the template).
Because of the CSS styling needed with this directive, I have used scope: false.
<span class="scoop-badge-content">{{$parent.getArea()}}</span>
Or in directive :
scope:true
This is because ng-if use how own scope
The strange thing is that when i have this problem i usually use dot notation. But it doesn't work here, probably because we're inside a directive, and i didn't had the case until now.
EDIT : a last way of doing this chaging the template :
<div class="scoop-badge scoop-badge-ua">
<div ng-if="isRestricted()">
<span class="scoop-badge-title">You are limited to:</span>
<span class="scoop-badge-content">{{getArea()}}</span>
</div>
</div>
I think this work because you have replace true and ng-if will conflict with ng-scope if it's on the top DOM element.
When you have scope = {} in your directive, Angular creates an isolated scope. Which means it can't get to the getArea() function.
You can completely remove the scope = {} line or set it to scope = true or scope = false depending on what you're trying to achieve later on.
When set to scope = true Angular will create a new scope object and assign it to the directive. This scope object is prototypically inherited from its parent scope.
When set to scope = false the directive will use its parent scope. (This is the default value. It has the same effect if you remove this line).
More information about scopes here
Removing scope: {} from directive definition solves problem.
app.directive('scoopBadgeUa', function() {
return {
restrict : "A",
scope: {}, // This is not needed, creates conflict
templateUrl : "scoop-badge-ua.html",
replace : true,
controller : 'ScoopBadgeUaController',
};
});
Your code is correct, you don't have to do anything more than adding a <div></div> wrapping your code in scoop-badge-ua.html.
<div>
<div class="scoop-badge scoop-badge-ua" ng-class="{'visible': isRestricted()}" ng-if="isRestricted()">
<span class="scoop-badge-title">You are limited to:</span>
<span class="scoop-badge-content">{{getArea()}}</span>
</div>
</div>
I like this solution better than transclude: true because it doesn't include the directive's tag in your html code, which ultimately translates to a cleaner code.

2-way binding for directive not working

I have a custom Angular directive, and it has an isolated scope having a value base mapped as 2-way binding
base="="
From the parent scope I pass base to directive as
and in the directive controller I am modifying this base value. The base is not just an object but a json structure having arrays within itself. I transverse to few fields inside base and then change those field value. For example one field is changed from 0 to 1.
Now, In another method in parent controller, I pick this base from original JSON, from where it was passed to directive. I expect the values changed in directive to be reflected in original JSON object.
Unfortunately that's not happening. I guess 2-way binding prefixes should make it possible.
I am sorry, since the directive template is too big, I am not currently uploading it. I will try uploading a miniature version later if possible.
In the meanwhile, Am I going wrong somewhere, Is there specifically something that needs to be done.?
A working fiddle illustrating this might help. I googled out and found something known as $broadcast and $emit. I am not sure how to use them in this case, and also I have never used them before.
Expecting little help guys..
Edit:
return {
scope: {
parent: '='
item: '=',
},
controller: 'ctrlname',
templateUrl:'tplname',
link: function (scope, element, attr) {
}
in html something like:
<li ng-repeat= l in originalJSON>
-----------something here------
<li ng-repeat= base in l>
---------something here-------
<li ng-repeat="x in base.y">
<div layout="row" layout-wrap directive-name parent="base" item="item" ></div>
</li>
</li>
</li>
Sorry it was '='
Just to add one more important info. In the parent controller, I am trying to access the originalJSON and looking for modified field in the base field inside it.
Can't you share the base object using services/factories. Also is the parent scope a directive?
The issue you have is multiple directives binding two ways to the same object.
This line appears several times (equal to the number of items in base):
<div layout="row" layout-wrap directive-name parent="base" item="item" ></div>
So you have several two way bindings between parent and base. These are all sitting in a for loop which will be watching base for any changes and updating the loop as necessary. I imagine that this could easily cause issues in your code.
Perhaps, you can bind to x instead?
Edit to clarify (as requested by comment):
You have your 'base' object which is being updated, this is using two way binding on multiple directives. Thus, you have:
base object 'a' being kept in sync with object 'b' in directive 1.
base object 'a' being kept in sync with object 'c' in directive 2.
base object 'a' being kept in sync with object 'd' in directive 3.
and so on in your for-loop. Then, as your directives are being processed, you have some logic to update b,c and d - which in turn you expect to update a. These events will probably all be firing at the same time. Each time they do fire, your for loop, which is looping over elements in a, recognises that 'a' has changed and says 'lets calculate the results of this for loop again'. Then each of the directives are going to be created again - perhaps firing off some more logic to change a.
There is not enough information in your question to tell that this is the problem, but hopefully you can see from my description that race conditions could be problem here. Binding to x in your for-loop instead (and having a one way binding to the base object if it is needed) should be a safer way of achieving what you want.
# is not a two way binding, for two way binding you need to use =
scope: {
"twoway": "=" // two way binding
},

Pass information to ng-repeat ng-include scope

I'm pulling my hair about a particular issue with my AngularJS application.
Basically, I have a controller, "PageCtrl", which pulls in a list of data via a service. The data is saved inside the PageCtrl. All works fine - so far so good.
Now my issue: for each object of the data inside the PageCtrl, I use ng-repeat to display each data just fetched.
In each of the ng-repeats, I use ng-include to get the correct template, depending of which data is in each object (basically the data is a list of elements that is to be displayed on the page. Each element has it's own controller.
As ng-include creates a newscope, all the created child scopes/controllers have access to the data, as it is located in the $parent controller - PageCtrl.
All works fine, except that each created controller in ng-repeat/ng-include needs to know which object in list of data in the parent, it needs to use to display.
Basically, in my ng-repeat, I would like to use the $index and pass it to the controller included in the ng-include. But I cannot do it! If I use ng-init, that code inside ng-init will be executed on the parent scope, ie. my original PageCtrl.
How can I, without the use of directives, pass information to the controller so that it knows which of the data-objects in its parent it should use?
Here is the code that loops over the data in MainCtrl:
<div ng-repeat="element in elements" >
<ng-include src=" GetTemplateFromElement(element.type) " ng-init=" SetElementNo($index); "></ng-include>
</div>
In the snippet, I call GetTemplateFromElement on the MainCtrl which returns the view to include. In the included view I refer which controller should do the work. I try to use $index to tell the included controller which index in the data it should use. But ofcourse the code is executed in MainCtrl scope. Example of a view:
<div ng-controller="ElementDocumentCtrl">
<div ng-bind-html-unsafe="element.document_content"></div>
</div>
In the snippet, "element.document_content" is on the scope of ElementDocumentCtrl, which pulls the data from its parent, PageCtrl.
How can I tell the directives included which index in the data-list in PageCtrl (it's parent controller) it should pick up?
Please don't tell me I need to make them all directives :)
Thanks, guys.
Maybe Im not understanding your question completely, but from the docs, $index, $first, $middle and $last are all exposed on the local scope of the ng-repeat children.
Ive put in a plunker to demonstrate this. The ChildCtrl accesses the $index from the parent to get the index of which element in the parent it is accessing.

Directive isolate scope with ng-repeat scope in AngularJS

I have a directive with an isolate-scope (so that I can reuse the directive in other places), and when I use this directive with an ng-repeat, it fails to work.
I have read all the documentation and Stack Overflow answers on this topic and understand the issues. I believe I have avoided all the usual gotchas.
So I understand that my code fails because of the scope created by the ng-repeat directive. My own directive creates an isolate-scope and does a two-way data-binding to an object in the parent scope. My directive will assign a new object-value to this bound variable and this works perfectly when my directive is used without ng-repeat (the parent variable is updated correctly). However, with ng-repeat, the assignment creates a new variable in the ng-repeat scope and the parent variable does not see the change. All this is as expected based on what I have read.
I have also read that when there are multiple directives on a given element, only one scope is created. And that a priority can be set in each directive to define the order in which the directives are applied; the directives are sorted by priority and then their compile functions are called (search for the word priority at http://docs.angularjs.org/guide/directive).
So I was hoping I could use priority to make sure that my directive runs first and ends up creating an isolate-scope, and when ng-repeat runs, it re-uses the isolate-scope instead of creating a scope that prototypically inherits from the parent scope. The ng-repeat documentation states that that directive runs at priority level 1000. It is not clear whether 1 is a higher priority level or a lower priority level. When I used priority level 1 in my directive, it did not make a difference, so I tried 2000. But that makes things worse: my two-way bindings become undefined and my directive does not display anything.
I have created a fiddle to show my issue. I have commented out the priority setting in my directive. I have a list of name objects and a directive called name-row that shows the first and last name fields in the name object. When a displayed name is clicked, I want it to set a selected variable in the main scope. The array of names, the selected variable are passed to the name-row directive using two-way data-binding.
I know how to get this to work by calling functions in the main scope. I also know that if selected is inside another object, and I bind to the outer object, things would work. But I am not interested in those solutions at the moment.
Instead, the questions I have are:
How do I prevent ng-repeat from creating a scope that prototypically inherits from the parent scope, and instead have it use my directive's isolate-scope?
Why is priority level 2000 in my directive not working?
Using Batarang, is it possible to know what type of scope is in use?
Okay, through a lot of the comments above, I have discovered the confusion. First, a couple of points of clarification:
ngRepeat does not affect your chosen isolate scope
the parameters passed into ngRepeat for use on your directive's attributes do use a prototypically-inherited scope
the reason your directive doesn't work has nothing to do with the isolate scope
Here's an example of the same code but with the directive removed:
<li ng-repeat="name in names"
ng-class="{ active: $index == selected }"
ng-click="selected = $index">
{{$index}}: {{name.first}} {{name.last}}
</li>
Here is a JSFiddle demonstrating that it won't work. You get the exact same results as in your directive.
Why doesn't it work? Because scopes in AngularJS use prototypical inheritance. The value selected on your parent scope is a primitive. In JavaScript, this means that it will be overwritten when a child sets the same value. There is a golden rule in AngularJS scopes: model values should always have a . in them. That is, they should never be primitives. See this SO answer for more information.
Here is a picture of what the scopes initially look like.
After clicking the first item, the scopes now look like this:
Notice that a new selected property was created on the ngRepeat scope. The controller scope 003 was not altered.
You can probably guess what happens when we click on the second item:
So your issue is actually not caused by ngRepeat at all - it's caused by breaking a golden rule in AngularJS. The way to fix it is to simply use an object property:
$scope.state = { selected: undefined };
<li ng-repeat="name in names"
ng-class="{ active: $index == state.selected }"
ng-click="state.selected = $index">
{{$index}}: {{name.first}} {{name.last}}
</li>
Here is a second JSFiddle showing this works too.
Here is what the scopes look like initially:
After clicking the first item:
Here, the controller scope is being affected, as desired.
Also, to prove that this will still work with your directive with an isolate scope (because, again, this has nothing to do with your problem), here is a JSFiddle for that too, the view must reflect the object. You'll note that the only necessary change was to use an object instead of a primitive.
Scopes initially:
Scopes after clicking on the first item:
To conclude: once again, your issue isn't with the isolate scope and it isn't with how ngRepeat works. Your problem is that you're breaking a rule that is known to lead to this very problem. Models in AngularJS should always have a ..
Without directly trying to avoid answering your questions, instead take a look at the following fiddle:
http://jsfiddle.net/dVPLM/
Key point is that instead of trying to fight and change the conventional behaviour of Angular, you could structure your directive to work with ng-repeat as opposed to trying to override it.
In your template:
<name-row
in-names-list="names"
io-selected="selected">
</name-row>
In your directive:
template:
' <ul>' +
' <li ng-repeat="name in inNamesList" ng-class="activeClass($index)" >' +
' <a ng-click="setSelected($index)">' +
' {{$index}} - {{name.first}} {{name.last}}' +
' </a>' +
' </li>' +
' </ul>'
In response to your questions:
ng-repeat will create a scope, you really shouldn't be trying to change this.
Priority in directives isn't just execution order - see: AngularJS : How does the HTML compiler arrange the order for compiling?
In Batarang, if you check the performance tab, you can see the expressions bound for each scope, and check if this matches your expectations.

Tricky scope binding in angularjs directives

I want to write 'edit in place' directive in angularjs.
I want that directive is reusable, therefore I have following requirements on the directive:
it must be an attirbute that can deocorate any element, that makes sense (div,span,li)
it must support edit button, clicking on that will change set ot displayd elements into input fileds. Typically properties of one object, e.g. contact (number, name)
I disocvere trickery behaviour of scope visibility in the directive that can be seen in this fiddle http://jsfiddle.net/honzajde/ZgNbU/1/.
Comenting out in the directive: template and scope -> contact.number and contact.name are displayed
Comenting out in the directive: scope -> contact.number only is displayed
Not commenting out anything -> nothing is displayed
=> when both are commented out just adding template to the directive makes it render contact.number even though template is not used.
I am asking what are the rules of the game?
<div>
<div ng-controller="ContactsCtrl">
<h2>Contacts</h2>
<br />
<ul>
<li ng-repeat="contact in contacts">
<span edit-in-place="" ng-bind="contact.number"></span> |
<span edit-in-place="" >{{contact.name}}</span>
</li>
</ul>
<br />
<p>Here we repeat the contacts to ensure bindings work:</p>
<br />
<ul>
<li ng-repeat="contact in contacts">
{{contact.number}} | {{contact.name}}
</li>
</ul>
</div>
</div>
var app = angular.module( 'myApp', [] );
app.directive( 'editInPlace', function() {
return {
restrict: 'A',
//scope: { contact:"=" },
template: '<span ng-click="edit()" ng-bind="value"></span><input ng-model="value"></input>',
link: function ( $scope, element, attrs ) {
// Let's get a reference to the input element, as we'll want to reference it.
var inputElement = angular.element( element.children()[1] );
// This directive should have a set class so we can style it.
element.addClass( 'edit-in-place' );
// Initially, we're not editing.
$scope.editing = false;
// ng-click handler to activate edit-in-place
$scope.edit = function () {
$scope.editing = true;
// We control display through a class on the directive itself. See the CSS.
element.addClass( 'active' );
// And we must focus the element.
// `angular.element()` provides a chainable array, like jQuery so to access a native DOM function,
// we have to reference the first element in the array.
inputElement[0].focus();
};
// When we leave the input, we're done editing.
inputElement.prop( 'onblur', function() {
$scope.editing = false;
element.removeClass( 'active' );
});
}
};
});
app.controller('ContactsCtrl', function ( $scope ) {
$scope.contacts = [
{ number: '+25480989333', name: 'sharon'},
{ number: '+42079872232', name: 'steve'}
];
});
You are running into problems because you are misusing angular.
First, a directive should be self-contained, but you are pulling functionality out of it, which makes it less universal and less reusable. In your code, you have functionality in the DOM and in the controller that belongs in the directive. Why?
Second, it's also unclear from your markup and javascript specifically want you want to accomplish when all these pieces are strung together.
Third, in most cases, directives should have their own isolated scope, which is done by declaring a scope object with attributes it should bind. You shouldn't be passing an expression (i.e. {{contact.name}}) inside the directive as it will break the binding and your contact will not be updated when the edit-in-place finishes. The proper way is to establish bi-directional binding through an = property on the scope. ng-bind isn't what you want here: that's scope-specific, so we use it inside the directive's scope. As Valentyn suggested, you could do some magic to get around this, but it's not a good idea and it's super-simple to set it up the right way. What's the issue with doing this by an attribute?
This is all bad Ju-ju.
As I pointed out in your other question on this same topic, you must make your directive self-contained and work with angular, rather than against it. Here's an attribute-based version of the fiddle I gave you previously, meeting the first of your requirements. Please let me know what is wrong specifically with this implementation and we can talk about the angular way of fixing it.
Lastly, if you provide further context on what you need in terms of a "button", I'll incorporate that into the fiddle too.
[update]
It is possible to make the directives work your way, but you will run into problems eventually (or right now, it would seem). All components in an angular app (or any app for that matter) should be as self-contained as is feasible. It's not a "rule" or limitation; it's a "best practice". Similarly, communication between directive components can occur through a controller, but it shouldn't. Ideally, you shouldn't reference the DOM in a controller at all - that's what directives are for.
If your specific purpose is a row that is editable, then that is your directive. It's okay to have a lower-level generic edit-in-place directive that the larger directive uses, but there is still the higher-level directive too. The higher-level directive encapsulates the logic between them. This higher-level component would then require a contact object.
Lastly, no, there isn't necessarily a big difference between ng-bind="var" and {{var}}. But that's not the issue; the issue was where that binding takes place. In your example, a value was passed to the directive instead of a bi-directionally-bound variable. My point was that the directive needs access to the variable so it can change it.
Summary: You are coding in a very jQuery-style way. That's great for coding in jQuery, but it doesn't work so well when coding in Angular. In fact, it causes a lot of problems, like the ones you're experiencing. In jQuery, you would, for example, dynamically insert DOM elements, declare and handle events, and manually bind variables all within a single code block, all manually. In Angular, there is a clean separation of concerns and most of the binding is automatic. In most cases, it leads to javascript code at least two-thirds smaller than the jQuery alternative. This is one of those cases.
That said, I have created a Plunker that contains a more sophisticated version of both the edit-in-place as well as a new higher-level directive to incorporate additional features: http://plnkr.co/edit/LVUIQD?p=preview.
I hope this helps.
[update 2]
These are the answers to your new round of questions. They may be good for your edification, but I already gave you the "angular way" to fix your problem. You will also find that I already addressed these questions (in broader strokes) earlier in my original answer as well as in my update. Hopefully, this makes it more apparent.
Question: "Comenting out in the directive: template and scope -> contact.number and contact.name are displayed"
My Reply: When you do not specify a scope, the directive inherits its parent scope. You bound and interpolated the name and number within the context of the parent, so it "works". Because the directive will alter the value, however, this is not a good way way to solve it. It really should have its own scope.
Question: "Comenting out in the directive: scope -> contact.number only is displayed"
My Reply: You bound a scope property of the parent to the "contact.number" directive, so it will get placed inside during the $digest loop - after the directive has been processed. On the "contact.name", you put it inside the directive, which can only work if the directive codes for transclusion.
Question: "Not commenting out anything -> nothing is displayed"
My Reply: Right. If the directive has its own scope (and this one definitely should), then you must use a defined directive scope property to communicate values, as my several code samples demonstrate. Your code, however, tries to use the parent scope in the directive when we explicitly forbid that by using the scope property in its definition.
Summary: While this second update may be informative (and I hope that it is), it doesn't answer the question beneath your questions: how do I use angular components correctly so that the scope I'm using is always what I think it is? My first post and the subsequent update, answer that question.
Here is little bit updated your fiddle, but it need further improvements to meet full list of your requirements: http://jsfiddle.net/5VRFE/
Key point is:
scope: { value:"=editInPlace" },
Some notes: its better to use ng-show ng-hide directivies for visual appearing-hiding instead of changing css classes. Also its better to spread functionality into different directives to have better separation of concerns (check ngBlur directive)
About your confusion of scope check guide about scopes paragraph "Understanding Transclusion and Scopes": Each directive have separate isolated scopes, if you want to have access from directive's template to controller's scope use directive scope binging ("scope" field of directive definition object). And also transcluded elements have a scope of from where you defined transcluding template.
From the first view those isolated scope sounds little bit strange, but when you have good structured directives (note also that one directive can require another and share bindings) you can find it extremly usefull.

Resources