Angular Directive Linking Order

A lot of people ask me this following question – “What is the right order of linking in nested directives”, so I made this following example to refer people to in the future:

.directive("testParent", function(){

        return {
            restrict: "E",
            template: "",
            controller: function(){
                console.log("testParent Controller");
            },
            compile: function(tElement, tAttrs){
                return {
                    pre: function (scope, element, attrs){
                        console.log("testParent preLink");
                    },
                    post: function (scope, element, attrs){
                        console.log("testParent postLink");
                    }
                }
            }
        }
    })
    .directive("testChild", function(){
        return {
            controller: function(){
                console.log("testChild Controller");
            },
            restrict: "E",
            compile: function(tElement, tAttrs){
                return {
                    pre: function (scope, element, attrs){
                        console.log("testChild preLink");
                    },
                    post: function (scope, element, attrs){
                        console.log("testChild postLink");
                    }
                }
            }
        }

This is what you’ll see in the console.log -

testParent Controller
testParent preLink
testChild Controller
testChild preLink
testChild postLink
testParent postLink

Conclusion
When you define the “link” property it’s a shortcut for defining the “post” property in the return object of the “compile” property, so you can understand from the console log that the right order of things is first the “link” of the child directive gets called and only after it the parent directive’s “link” gets called.

Yeoman Bower and Grunt – Building Modern Webapps With Ease

The Google Developers Group’s organizers asked me to come and speak at their last meetup (22/5/13) about Yeoman and I was really happy about it, because after my last lecture about Angular, a lot of people asked me about the “auto refresh magic” I’ve done on every file save.

So I wanted to spread the word about Yeoman, Grunt and Bower because I think they are very important tools in every FED’s tool belt.

So here it is, hope you’ll enjoy it:

 

Here are the slides:

Angular UI-Router – State templateUrl and views Issue

I’ve been following the ui-router for quite some time now.

Basically it’s a state machine implementation for Angular.js, which is pretty awesome!

Today I’ve found myself wasting time trying to figure out something that should be trivial.

In a the ui-router you can define a state configuration with a “views” property which represent the ‘ui-view’ names you have in your state’s template.

I thought you should be able to define a state, and a nested views objects with it’s template & controller injections (looked like the trivial thing to do).

But when I tried it…

This showed nothing when I went to ‘/mystate’: 

 $stateProvider.state("myState", {
  url:"/mystate",
  templateUrl: mystate.tpl.html",
  controller: "myStateCtrl",
  views: {
    'substate1': {
       templateUrl: 'substate1.tpl.html',
       controller: 'subState1Ctrl'
     }
  }
 })

// mystate.tpl.html
<div>
   <div ui-view="substate1"></div>
</div>

 

So I read and re-read the documentation trying to find a clue for whats happening, but no luck.

After some time I found an open issue describing this weird behavior, where they stated that if you define a “views” property, it automatically ignores any high level template properties you defined.

 $stateProvider.state("myState", {
  url:"/mystate",
  templateUrl: mystate.tpl.html",  -> this is being ignored
  controller: "myStateCtrl",
  views: {
    'substate1': {
       templateUrl: 'substate1.tpl.html',
       controller: 'subState1Ctrl'
     }
  }
 })

I tested it with a different variation (see below), and it worked, so I  updated the documentation to save the time for the rest of us.

 

Different variation

I figured out that the right way to define an abstract state, and to go to it’s sub state url.

This worked when I went to ‘/mystate/substate1′ : 

$stateProvider
.state("myState", 
  url:"/mystate",
  abstract: true, 
  templateUrl: mystate.tpl.html",
  controller: "myStateCtrl"
 })

.state("myState.subState1", {
  url:"/substate1",
  views: {
    'substate1': {
       templateUrl: 'substate1.tpl.html',
       controller: 'subState1Ctrl'
     }
  }
 })

// mystate.tpl.html 
<div> <div ui-view="substate1"></div> </div>

Conclusion:

When you define the ‘views’ property, be aware that the ‘templateUrl’ / ‘template’ / ‘templateProvider’ properties will be ignored, so declare an abstract state with the “Layout” and define sub states with the template & controller injections.

I’m on Google Developers’ YouTube Channel – Talking about Angular.js

This Wednesday I was hosted by Ido Green from Google on their show “Google Developer Live”.

It was fun and I had the chance to yap about Angular.js for half an hour or so which is always good.

We will probably have together further episodes on more advanced angular stuff and it got me wondering whether to start doing my meetup lectures in English.. hmm…

And here are the slides from the screencast:

My Angular Introduction Talk

Hi guys, last month I gave an introduction to Angular.js (in my native tongue – Hebrew), at the Google TLV Campus and it was a lot of fun.

This talk was part of a new group I opened on meetup called – “Javascript Israel“, and the reason I opened up this group was to have better way for people (including myself) to learn faster by raising the amount of meetups and lectures we have here in Israel and giving another platform to share knowledge and to meet other developers.

We are having two events this week, one about ember.js, hosted by Google, and the other one about advanced angular topics, hosted by Wix, in which I’m giving another talk about directives.

So here is my talk in case you want to see me mumbling:

And here are the slides:

My first podcast interview… :)

This week I had the privilege of being on the Reversim Podcast – The biggest technology podcast in Israel (Respect!)

I’ve been listening to this podcast for several years now while driving to and from work and while running (when I wasn’t such a slob), and learned a lot of new concepts over the years and a lot of useful information that helped me to better understand the tech world around me.

We talked about Angular.js (in Hebrew) and what it is all about. A little bit about MVC, Testing, comparison with Backbone and Ember and also about Yeoman.

Also got the chance to mention the meetup group Javascript Israel I’m currently running, and spread the word to relevant potential sponsors.

It was very fun discussing it with Ran Tavory (which I’m a fan of) and hear his point of view on the same issues I’ve been trying to tackle for quite some time now. It turns out that I’m not alone in my point of view on the architecture mess called MVC.

And I’ll end on this – The more I use Angular the happier I become… so if you haven’t try it yet, go ahead and give it a go

Angular.js Large Scale Architecture and StarCraft

While preparing for a recent lecture I gave about angular.js I thought about how to deliver the point on angular’s architecture for large scale application.
So I came up with a metaphor that I feel make sense, (hint: StarCraft related) so I thought I’d share it today and see what you guys/girls think of it.

null

MV(whatever)

Ever since I learned about MVC few years ago I’ve been feeling that something is missing. MVC was meant to model how human think and apply it to software design.

So the concept of breaking your app into well defined pieces is absolutely wonderful, but I always felt that Models, Views & Controllers aren’t enough when you’re dealing with orchestration, coordination and maintenance of large scale applications.

With all of the multiple variations of client side architecture patterns (MVC, MVP, MVVM, MVA, etc…) and their Javascript frameworks implementations, I was left with more questions than answers. It seems that every framework suggest something slightly different and confusing.

For example – the location of business logic, sometimes it’s in the controllers, other times in the models, and where do I put the remote services or proxies under?
Some frameworks use a view model, others only a controllers. Some frameworks call it a model, others call it entity.

You get the point – it’s confusing, but instead of solving the issue, we just name it MV* (star) and move on with our lives, dazed and confused.

MV*


There was a point when I considered DCI as a good replacement for the MVC pattern, but haven’t got around to actually test this theory in the field. Luckily, I wasn’t have to, because after moving between different MVC frameworks (JMVC, Ember), I finally got to code with Angular.js and everything finally fell into place.

Angular – Service Oriented Architecture (SOA)

I know being called a MVC framework is the fashionable thing these days, but Angular.js isn’t really MVC.
Its controllers are actually presentation models, its views are plain templates and it’s models… well.. there aren’t any, they are just plain old objects and arrays.

Angular also introduce a few cross cutting concepts like Services, Directives and Filters, that you won’t find on any other framework (as part of the core). And that’s where I think angular is actually far ahead in terms of large scale application design.

Large Scale Architecture – The StarCraft Way

If MVC is modeling the human brain, Angular.js is more like modeling the Zerg Overmind.

Angular.js Architecture - Shairez

You have the services layer, which is like a giant application brain that handles all of the state coordination, data persistence and the business logic, which is like the Zerg Overmind, it knows everything and can answer anything.
(just thought about the idea that Zerg Overmind === Google … hmm… )

The angular “controllers” are like mini brains, less capable, and responsible of view specific tasks, just like the Zerglings’ brain who knows just how to Kill Humans or Protoss, and occasionally hit a brick wall or something.

Templates and directives are like sensors and speech, which are responsible for displaying or “speaking” data to the user, and to take in outside information (like user events or data) and pass it to the controller.

When you want to extend your application cross cutting capabilities, you add a service, a filter or a directive. And when you want to add another screen or page specific view, you can add a template/controller pair.

Just like when you want a strategic action (like upgrading your units’ armor) you call the Overmind (its structures) to do that, but when you want tactic actions (like killing a Protoss) you send a Zerg unit with its mini brain and sensors to get the job done.

Conclusion

This is how I like to look at the different angular architecture parts, but that’s just me, I’d love to hear what you think.

Closures, Hoisting, Scope and the true order of things

While reading a nice post with 4 trivia questions in Javascript, thinking to myself: “ohh.. that should be easy to solve”…

One question got me confused, and it was:

“What is the next function’s result should be?”

function outer(){
   var x=1;
   var inner = function(){
      alert(">"+x);
   }
   x=2;
   return inner;
}

outer()();

Well… the result was:

alert ‘>2′

And I looked at it, confused a bit, trying to figure out.. wait.. why isn’t it “ alert ‘>1′ ” ?

I read Javascript: the definitive guide, and I know all about Hoisting and what is the difference between Function declaration and Function expression hoisting.
So why I can’t figure out why it doesn’t show the correct value?

Apparently, I got the wrong idea about something very critical… :)


By reference, not by value, dummy

At the javascript bible i mentioned before, it was written that:

Javascript uses Lexical scoping. This means that functions are executed using the variable scope that was in effect when they were defined, not the variable scope that is in effect when they are invoked.

I misunderstood it for saying:

Functions are taking a snapshot of the current state of the variables they can see up until that point in time, because the JS interpreter goes from top to bottom, meaning that the order of things matter.

I thought that:

The state that was before the function was defined is what it will remember, like it stores a copy of all the values of the variables assigned before it.
And when the example’s inner function was defined, the state of x was “1″.

But I was wrong:

Actually, The inner function, gets a reference to the variable binding object, which is part of the scope chain, an that object holds references to the local and other visible variables of that inner function. Meaning that if variables continue to change on the outer function invocation instance, sure enough the same inner function and its references will reflect it.
So the point of time of the function invocation matters, not only the definition. (a point to remember!)

I made a little fiddle for you to play with and get the point.

Hope it helps anyone who got it wrong like I did :)

Shai