Sunday, October 16, 2016

Directives and Data Binding Syntax in Angular JS

Here’s an example of using a very basic, but important, Angular directive. 

Notice at the top we have ng-app. Any time you see ng- that is an Angular directive. It’s a built-on directive. You can also write custom ones. You can get third party ones and things like that. 

This particular directive is very important because the script that’s now loaded [at the bottom] is going to kick off and this will initialise the Angular app. Right now we don’t have any particular module associated or any other code but we can still do stuff just by adding ng-app. 

So for example, this is an example of another directive called ng-model. 

What ng-model does is behind the scenes it’s going to add a property up in the memory called “name” into what’s called “the scope”. 

If you’ve ever dealt with the concept of a View’s model called a ViewModel - Knockout and some other libraries have this concept – then what this is really doing behind the scenes is making an empty ViewModel but then filling it with a name property. Now if I want to write out that value then I can simply come over and add a data binding expression. 

Expressions are really cool because if I wanted to put “1 + 1” and try to write out the result I could do that. You can’t put conditional logic in here because you shouldn’t be putting that type of conditional logic in your views. But out of the box, just by adding the ng-app and ng-model with a property as they type into this text box I can actually bind to that value and that provides a very cool little feature.

No comments:
Write comments
Recommended Posts × +