Angular Directives 2 way binding & refresh

911 Views Asked by At

Let's say you have a page where you have a directive for customer search (1st directive). You do a search and you get back a list of customers from a web server.

Now, inside the directive above, you have a 2nd directive, let's call it customerRes, that displays some info for the customers (this is like a small widget reused in many places in your site). Inside the isolated scope of this 2nd directive I have an attribute called results that I bound from the results returned e.g.

The 1st directive has a declaration like

<customer-res results="webserverResult">

and inside the customerRes directive I have something like a

<div ng-repeat="x in results>
{{name}} {{bla}}  ... bla bla
</div>

Now everytime the user clicks the parent directive, it will make a request to the web server and perhaps get different results back.

The question: Does angular actually monitor itself that the value bound to the isolated scope changed outside the directive, or do I need to do something to make sure that it invalidates?

Also, even if you load your page before the results get back, once they get back shouldn't they update the page elements?

1

There are 1 best solutions below

3
On BEST ANSWER

A cool way is you will find out for yourself. Don't get me wrong, but personally I did this when walking my first steps in angular. Helps to understand the framework more deeply rather reading the docs and forget more easily.

You can always add

scope.$watch('myVariable', function(value) { 
  console.log('myVariable changed to:', value);
})

to your directives and see when its value changes.

Two-way-bindig works like a charm, even on full page reloads. Cannot be more precise without your directive's JS code. But when using isolated scopes, probably directives need

scope: {
   myVariable: '='
}
<my-directive my-variable="results.entries"></my-directive>

But keep in mind, that when reloading the page, angular restarts from zero. Meaning for each directive its link function is called once and many many other things under the hood. Keyword is angular's digest cycle.

Hope I could help with this (a bit more broad) answer.