AngularJS directive, scope - javascript

hey I have a question
If in directive I use scope {}. Then I know that is create local scope. but could someone tell me how it looks. Because I have a problem with understanding it.
It is so that If i add dom attribute, for example card
<div modal-window-card card="card" ng-model="text"></div>
Then whole variable with $scope.card is assigned to this card where next, I can modificate everything in the directive like in function yes?
But why I can't write all value from variable in :
link: function(card) {
console.log(card)
},
And one more thing, whole directive is like in new local scope yes? I mean, all functions, which are located in the directive is in this scope yes?
for example
<buton ng-click="fefe()">start</buton>
If i click start buton it will execute function with the directive, yes? if i set ng-click="$parent.fefe()" then after click it will execute function with parent scope, yes?

You are using link incorrectly. The signature is link(scope, element, attrs). As for the other questions, yes and yes, assuming your buton is within the directive's template.

Related

Can I access parent scope from inner HTML of an element with an isolate scope attribute?

I have an attribute directive 'my-isolate-directive' that decorates the value of the HTML element to which it is attached. I made it an isolate scope so I can pass params to it.
But I'd also like to continue referencing objects in the parent scope - e.g. 'outerVar' below - from within the value of the element that has the attribute directive:
<div>
'outerVar' shows! {{outerVar}}
</div>
<div my-isolate-directive my-isolate-directive-param="requiredParam">
Oops! 'outerVar' does not show! {{outerVar}}
</div>
Is this possible?
It isn't. The purpose of the isolated scope is exactly to prevent what you're trying to achieve, by not inheriting from any other scope. If you wan't to access the parent scopes and still create a new one you should set scope: true.
As #Andrés says in his answer, scope: true lets your directive have a new scope inherited from the parent.
I will add that if you would like to have attributes without isolate scope, you still can by using something like:
attr.$observe('myIsolateDirectiveParam', function(myIsolateDirectiveParam){
scope.myIsolateDirectiveParam = scope.$eval(myIsolateDirectiveParam);
});

Angular custom directive - two way binding which always sets attribute to true or false

I'm creating a custom Angular directive for a slide in menu which needs to watch a couple of attributes and one of those attributes needs to be two way bound to the main controller scope (sometimes). However, sometimes the attribute will not be added by the developer so it needs to be added automatically and set to the default (false). So, the directive can be used like this.
<slide-menu position="right" is-open="menuIsOpen"></slide-menu>
or like this:
<slide-menu></slide-menu>
When used the first way the main controller will be able to open and close the menu by changing the value of the boolean $scope.menuIsOpen.
When used without supplying the is-open attribute it should default to false and is obviously used internally and by a child toggle directive.
An additional complication is that whether the attribute is supplied by the developer or not it should exist in the DOM. so in the second example above the directive would set itself to false by default and add the attribute is-open="false" to the DOM?
The reason for requiring is-open="false/true" in the DOM at all times is that the menu is actually operated using CSS tansitions which use the following selector:
slide-menu[is-active="true"]{
// Slide the menu in using transforms/transitions
}
There is a jsfiddle here which shows how far I have got.
http://jsfiddle.net/jonhobbs/gEPvE/
Obviously it doesn't work, but it shows how I have tried to set a default and how I have tried to use # and & on the isolated scope for a one time binding (the menu position) and a 2 way bound expression for the is-open variable.
I'm clearly a long way from achieving what I need but any advice would really be appreciated.
Have a look at this fiddle http://jsfiddle.net/gEPvE/38/
I took the one you started and updated it to act like you specified.
You can make a two way binding value optional by adding a ? on the scope definition.
Like this
{
scope: {
'isOpen':'=?'
}
}
Now the is-open attribute is optional.
Then you can set the default value in the directive controller, like you had started to do.
Next, in order to synchronize the DOM attribute with the scope value you can use $watch.
$scope.$watch('isOpen', function(val) {
$element.attr('is-open', val);
});
Finally, I changed the second 'slideMenuToggle' directive to wrap/transclude its element in order to add an ng-click handler. This is mainly to avoid any nastiness with calling $scope.$apply yourself.
Let me know if that works for you.
EDIT
Answering your question in the comment, you can pass a value directly without having it be bound to the scope, you just need to wrap the value in quotes.
For example
<div ng-controller='ctrl'>
<hello world='imOnScope'></hello>
</div>
Assuming 'hello' is a directive with a scope of 'world': '=?' then angular will assign a reference to the parent scope's 'imOnScope' object to the directive's $scope.world member, allowing a two way binding scenario.
To just provide a value directly you may do something like this
<div ng-controller="ctrl">
<hello world="'directValue'"></hello>
</div>
In this scenario angular will just assign 'directValue' to the directive's $scope.world member.
You need to add ngTouch to your module.
var app = angular.module('app', ['ngTouch']);
And add this script:
http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-touch.js
The reason for requiring is-open="false/true" in the DOM at all times
is that the menu is actually operated using CSS tansitions which use
the following selector
Forcing directive attributes to be appropriate for css selectors is terrible idea. As you correctly stated, they are for developers. So add a class to the element dynamically.
It seems that you're misusing &, it would be ok to set up a callback, but since you don't do this, in its current state you can end up with one-way # with confidence.
I guess it can be something like this (just added ngTouch and ng-controller for parent scope).
You could replace
$scope.watch('isOpen', function () {
$element.toggleClass('opened', $scope.isOpen);
});
with
$scope.watch('isOpen', function () {
$attrs.isOpen = !!$scope.isOpen;
});
and get the behaviour you're asking for, easy as that. Ok, it is boolean now, and it reflects the scope, and you can use [is-open=true] selector. But guess what will happen with your binding? Broken. Fortunately, you can do
$scope.watch('isOpen', function () {
$element.attr('is-open', !!$scope.isOpen);
});
instead. Voila, we tricked Angular because it doesn't look after jqlite. But what will will happen with the binding when the directive will be re-compiled for any reason? Again, isOpen's binding is non-existing 'true' or 'false' scope variable. Broken.

AngularJS, binding to a model in ng-repeat in a directive

So I am trying to bind inside a directive (to access outside) to a model inside of an ng-repeat. So in the outer controller I have a variable I would like to bind in like
//in the directive scope
filterArray: '='
Inside the directive that would be bound inside the directive to a model in an ng-repeat like so -
//inside the directive
<li ng-repeat="value in filter.values">
<input type="checkbox" ng-model="filterObject[filter.name][value]" ng-change="filterChange()">{{value}}
</li>
This worked fine until I changed the directive to have an isolate scope, now it is saying cannot set property of undefined. Is there any way to get this working as intended? The idea is the variable would build out when the user clicks the inputs so the outer controller would be able to see the built object.
Apologies if this is a bit confusing - I have made a fiddle to clarify : https://jsfiddle.net/vt1uasw7/42/ .
I want the outer controller to have access to the object built by binding the model - again this was working before I added the isolate scope. Thanks!
Edit: maybe the trick in this case is not to use the isolate scope? This one has me stumped, I've tried every combination of scope attributes :(.
If you can't pre-initialize your outter filterObject you can let the directive controller handle that for you:
$scope.filterArray[$scope.filter.name] = {};
And check your parameters as Claies stated, inside your directive you need to use filterArray and also the attribute name in the outter ng-repeat needs to be "filter-array and not "filterArray".
<div ng-repeat="filter in searchResults.filters" class="my-directive" filter="filter" filter-change="filterChange" filter-array="filterObject"> </div>
See this https://jsfiddle.net/vt1uasw7/164/

AngularJS : Access to isolate scope with replace in directive

I want to know if there is a way to access the scope of directive if I have set the replace option to true. For example, here is the initial jsbin:
http://jsbin.com/ABuSODub/2/edit
When you click on x, the directive closes. close() function is defined on the directive's own isolate scope. However, if I set replace to true, the thing stops working which is understandable because there is no directive anymore.
Can it be made to work? It there a better approach. I really do not want to set close function on parent controller. Or is it some other problem entirely which I do not see?
If all you want to do with the click event is set open = false, you don't need to call a function to do that. Consider this template revision:
'<div class="alert-box {{box}}" data-ng-if="open" data-ng-init="open = false"><span data-ng-transclude></span>×</div>',

Angularjs isolates scope directive with ng-repeat

I'm trying to use directive on ng-repeat items each with an isolate scope but it isn't working. I'm looping through each item and coloring it red with the inboxuser-select directive. However, when I put the directive on, it doesn't show any of my scope values. What is the issue here? Thanks
html file
<li class="inbox-chatter" data-ng-
repeat="inboxuser in inboxusers">
<p inboxuser-select selected={{inboxuser}}">{{inboxuser}}</p>
</li>
directive.js
.directive('inboxuserSelect', function() {
return {
restrict: 'A',
scope: {
selected: "#"
},
link: function(scope, element, attrs) {
scope.selected.css('color','red');
}
}
});
The problem is that once you set an isolate scope on the directive then the whole DOM element has that isolate scope. So the inboxuser from your ng-repeat is no longer in scope when data binding occurs (it's on the parent scope).
One option is to set scope to true instead of using an isolate scope so you'll inherit everything from the parent scope.
Or you can stick with an isolate scope, but pass inboxuser in to the directive and display it using a template. Since you're already passing inboxuser in to the directive's scope through selected it'd be easy to just add this to your directive:
template: '{{selected}}',
Also, by the way, you're missing a quote on your <p>. So this might work better for you (note I also removed {{inboxuser}} from within the <p> assuming you'll be using the template to display that instead):
<p inboxuser-select selected="{{inboxuser}}"></p>
To be honest, I don't understand what you really need to do but I have a feeling that this design will not get you there.
However, I fixed your example just for the purposes of explaining how things work.
You can see it live here.
So... when you write:
scope: {
selected: "#"
}
you are actually saying that my isolated scope will hold a single property named selected which will be of type string and will contain whatever {{inboxuser}} evaluates to. And not only this, whenever inboxuser changes in the outter scope, selected will also change in the inner, isolated scope. This is how '#' binding works.
Whatever you put nested in <p inboxuser-select selected="{{inboxuser}}"></p>, is binded to that isolated scope, which does not have an inboxuser property. So, it has to change to:
<p inboxuser-select selected="{{inboxuser}}">{{selected}}</p>
Finally, scope.selected.css('color','red'); should be changed to:
element.css('color','red');
The element argument in link function is the DOM element where the directive instance is applied. scope.selected is just a string.
I suggest you rething your overall design. If you need help, feel free to ask.
If it helps you, you can use AngScope, a tiny firebug extention i've written. It's just a quick way to inspect $scope instances associated to DOM elements inside firebug's DOM inspector.

Categories

Resources