- AngularJS provides two-way data binding. If data model changes, view is updated i.e, DOM of the webpage will refresh with new data and if new value is entered in field, data model will update.
- We can divide application into different components and AngularJS Dependency Injection mechanism will inject components into each other.
- Accessing DOM should be done only in Directives. Directives are AngularJS markers which adds behaviour to DOM element. Directives are added to HTML template to add dynamic behavior.
<div ng-repeat="c in book.notes track by $index"> <img ng-src="{{c}}" width="500" height="500"> </div>
- ng-repeat is a directive which instantiates template once per item( variable c) in collection(book.notes Array)
- If the value of book.notes =['link1.jpg','link2.jpg'] then view will be rendered with two div elements, one for each link in book.notes
- <input ng-model="book.note" >
ng-model directive stores/updates value of the input field. note is model field which will be updated based on input field.
HTML Template
Following is the HTML template we will use to display one input box which expects web page url and an add button which add link to image collection.
<div ng-app="notes" ng-controller="notesController as book"> <button ng-click="book.add()">Add</button> <input min="0" ng-model="book.note" required > <div ng-repeat="c in book.notes track by $index"> <img ng-src="{{c}}" width="500" height="500">
Controller View Model is defined in Controller file
angular.module('notes',[]) .controller('notesController',function(){ this.notes=[]; this.add=function (){ this.notes.push('http://screenshot.etf1.fr/?url='+this.note); };
- Controller is attached to DOM using ng-controller.
- All properties and methods defined inside controller are available in DOM where controller is attached. Properties are called view model and methods are called behaviour.
- notes is a model and add is behaviour which is available in DOM where ng-controller="notesController" is added.
When Add button is clicked the notes model is updated and view is updated accordingly because ng-repeat is based on notes model.
Complete HTML code and controller.js code
<html lang="en"> <head> <meta charset="UTF-8"> <title>Example</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script> <script src="controller.js"></script> </head> <body > <div ng-app="notes" ng-controller="notesController as book"> <button ng-click="book.add()">Add</button> <input min="0" ng-model="book.note" required > <div class="col-xs-3" ng-repeat="c in book.notes track by $index"> <img ng-src="{{c}}" width="500" height="500"> </img> </div> </body> </html>
Controller.js
angular.module('notes',[]) .controller('notesController',function(){ this.notes=[]; this.add=function (){ this.notes.push('http://screenshot.etf1.fr/?url='+this.note); }; })
No comments:
Post a Comment