I've been creating custom directives that involve initialization of data on load. Since this initialization depends on the state of scope objects from the parent bound to the isolate scope within my directives, I've been enclosing the directives in ng-if statements, so they are only rendered in the DOM, and therefore initialized, once the appropriate parent scope objects are created.
Ng-if seems preferable because the directives have various API calls bound to $watches that I would prefer to not trigger until the data is valid.
For example, I have a directive that provides an interface for editing a scheduled event. The parent page allows users to select an event for editing, or to create a new event. Creating a new event is done in a way that allows the user to select a variety of values to pre-populate the event object with (start dates, event type, whether the event is tied to another object in the database, etc.).
The ng-if wrapping the directive gets set to true when the user makes the selections necessary for working with the event, and the event (either an existing event, for edits, or a framework for an event created by a custom service, for adds) is bound to the isolate scope of the directive.
This prevents the $watches from triggering until the valid event is bound to the directive, and also allows me to initialize some variables local to the directive for validation and data manipulation of the event.
The problem I'm running in to is that enclosing the directive in an ng-if isolates the isolate scope.
For example, a start time for the event is something that may, or may not, be specified by the user when they create the new event from the controller. If they don't, I want to calculate a default start time based upon other variables within the directive. If they do, then I want to use that value.
The way I'm doing this is to bind a scope variable from the controller to the isolate scope of the directive:
scope: {
editEvent: '=',
overrideTime: '='
}
This is passed as an attribute of my directive:
<add-edit-event ng-if="viewEdit" event="editEvent" override-time="overrideTime">
</add-edit-slot>
Once the directive creates the new event (or cancels out), I want to reset that overrideTime in the parent scope to null.
To do that from within my directive, however, I can't rely on the two-way binding to work without traversing up past the ng-if scope, thus:
scope.$parent.$parent.overrideTime = null;
I keep running into situations like this, where the fact that the directive is enclosed in an ng-if causes complications with the scope, which makes me feel like there's a problem with my general approach.
Is there a better way of handling conditional initialization and loading of custom directives, or is enclosing them in ng-if statements okay, so long as I deal with the interposing ng-if's scope appropriately?
Related
What happens inside AngularJS when a event is fired with the Angular internal event system?
From a performance point of view, should I tend to use watches or events to update parts in my application?
When a JS event is fired, it is typically handled in the same way that all JS events are handled - there is nothing special or unique about this.
However, angular will wrap the handler inside of an $apply block so that after it executes the function, it can trigger a digest cycle:
$scope.$apply(function(){
$element.on('click',function(e){
...
});
})
A digest cycle iterates over all your scope variables, compares each one with the previous value to determine if anything has changed, and if it has, then their corresponding $watch handlers are called to update the view.
Since you are using angular, set up $watch expressions when you want to detect that a model on your scope has changed, and then do any DOM manipulations from inside your $watch handler. If you are concerned about performance, make sure your $watch function is optimized (i.e. avoid full jquery, avoid expensive query selectors, minimize DOM manipulation etc.)
To answer your question, you should use $watches to monitor changes to your models, and $watch functions to update your view.
I've written a pagination control directive that is bound to the view controller on pageNumber and pageSize. When either value updates, the view controller makes the appropriate, paged search and updates the data table. The directive is inserted twice, above and below the data table.
Plunker (you'll want your console open)
The trouble I'm having is that the events fire twice, once for each directive. I tried modifying it to 1-way bind pageSize and pass it as an option to setPage(), but then the two directives don't stay in sync with each other or the view controller (if it updates pageSize).
Normally, I'd use an isolated scope, but I think that won't work here. Can I make this work like I want?
Rather than having two directives implement one $watch each, move it up in the the parent controller, where it will fire only per value change. Then, if you need to propagate some value to both directives, do that with another isolate scope variable.
I'm trying to build a reusable directive that shows a dialog box when a button is clicked and allows the user to customize an array of strings. I have this working fine in a single-use-case scenario, but I'm trying to figure out if I can create two-way data binding through code, so that I can use a single instance of this directive multiple times with different arrays of strings.
In my HTML, I have the directive (note the lack of binding to a particular array):
<my-array-dialog control='arrayDialog'></my-array-dialog>
I'm exposing a shared control object with a showDialog method on it that causes the dialog to be shown. An example of that pattern is: http://plnkr.co/edit/MqN9yS8R5dnqTfjqldwX?p=preview
What I want to do is have two-way data-binding with the parent controller passing in the data into my showDialog method. I'm unsure how to configure this though, or even if it is possible.
In my directive, I have the following:
$scope.control = {
showDialog: function (arrayData) {
// Ideally, this would create two-way data binding
$scope.arrayData = arrayData;
// Manipulate the DOM here to show the dialog
}
}
Ideally, changes to $scope.arrayData would be reflected in the calling code's arrayData. Again, the reason I'm not setting this up as an attribute is because I want to call this dialog multiple times with different data and to avoid having multiple dialog directive instances.
Is it possible to set up the two-way data binding in this manner, or am I going about this all wrong?
Absolutely! Check out the intimidating yet incredibly helpful AngularJS docs page on $compile. In particular, what it sounds like you'd like to do is create a two-way binding between a parent scope variable and a variable in the local scope of the directive.
When defining a directive, you can specify a scope object. You'll want to create an isolate scope (for reusability) and use the # feature to create the two-way bindings with the HTML attributes.
From the $compile docs:
= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localModel:'=myAttr' }, then widget scope property localModel will reflect the value of parentModel on the parent scope. Any changes to parentModel will be reflected in localModel and any changes in localModel will reflect in parentModel.
I want to have a custom directive that is reusable and creates an isolate scope so it can be used anywhere (as long as the consumer uses the API defined by the directive). Then, I want the consumer to easily be able to mix and match different reusable pieces that fit within the main reusable directive.
The situation I'm working with is a drop down menu. The main directive would isolate the scope and define the API for the dropdown as a whole. The inner directives would allow the consumer to choose whether they want a button that opens the menu, a search box/input field that opens the menu, etc. Then they could also choose what menu style is used:
<dropdown items="..." selected-item="...">
<dropdown-button>(Transcluded button text here)</dropdown-button>
<dropdown-icon-list></dropdown-icon-list>
</dropdown>
The parent directive/controller would handle state/communication for the inner pieces (ie. the button might trigger the "open" state, and the list would respond by opening). In other words, the parent directive would provide a single place for the consumer to define behavior and isolate scope from the rest of the page, while the nested directives would change shared state/respond to changes in shared state based on their role.
I actually had this working by using an isolate scope on the main "dropdown" directive and then inheriting scope with the nested directives (didn't specify "scope: ..." on the nested directives). But, with Angular 1.2, things have changed such that the isolate scope of the parent is truly isolated--the children inherit the scope that exists outside the parent directive, rather than sharing its isolated scope.
What is the Angular way to accomplish such a thing?
I've started retrofitting my existing code to share the controller from the parent directive with the nested children, but I feel that's the wrong way to go once I get into the situation where the children need to listen for changes on the shared scope... The only way I can see to do that would be to pass a callback function from the nested directives into the shared controller which it would bind to a $scope.$on method. Seems like the wrong path to head down.
There’re 3 types of prefixes AngularJS provides.
"#" ( Text binding / one-way binding )
"=" ( Direct model binding / two-way binding )
"&" ( Behaviour binding / Method binding )
All these prefixes receives data from the attributes of the directive element and provide communication between directives. please visit below link for similar question.
Visit https://stackoverflow.com/a/33024209/4348824
Greetings Overflowers,
If I am changing an HTML native attribute (say a division's class) inside an event handler, do I need to wrap it with a call to $apply? In other words, are these native attributes watchable?
EXAMPLE:
I am doing a custom directive inside which I am modifying the element's classes for styling on certain events like mouse enter, but no modification to the scope (or model).
I am wondering if I need to surround this logic with a call to $apply just in case there is a $watch on these element's class attribute? Are these $watches possible using angularjs? My custom directive will be used by other programmers.
Kind regards
Any thing that Angular doesn't know about should be inside an $apply if you want bindings to be updated etc...
So no, this native attributes are not watchable if you manually change the DOM and it's not part of a user event or Angular's service event (like $http)