This article will take you through the views and instructions in Angularjs, I hope it will be helpful to you!
In the first article you saw how AngularJS splits the application into views , Controller and Model (MVC). This article takes an in-depth look at how to create AngularJS views. [Related tutorial recommendations: "angular tutorial"]
Before starting, let me first set up a simple AngularJS application that you can use to experience the examples in this article:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> </head> <body ng-app="myapp"> <div ng-controller="MyController" > <span></span> </div> <script> angular.module("myapp", []) .controller("MyController", function($scope) { //empty controller function }); </script> </body> </html>
AngularJS views mix data from the model into HTML templates. You can use AngularJSDirectives to tell AngularJS how to mix data into HTML templates. This article will cover the most commonly used AngularJS directives.
Interpolation directive
The interpolation directive is one of the most basic directives in AngujarJS. The interpolation directive inserts the result of an expression into an HTML template. You can use the {{ }}
symbol to mark where you insert an expression. Here's an example:
<div ng-controller="MyController" > <span> {{myData.text}} </span> </div>
HTML template is contained in a div
element with the ng-controller
attribute. Inside the HTML template is a span
element, and inside is an interpolation instruction. This directive instructs AngularJSmyData.text
to insert a data value at the given position.
The interpolation directive can also interpolate data returned from functions of the model object. Here is an example:
<div ng-controller="MyController" > <span>{{myData.textf()}}</span> </div> <script> angular.module("myapp", []) .controller("MyController", function($scope) { $scope.myData = {}; $scope.myData.textf = function() { return "A text from a function"; }; }); </script>
In this example, the interpolation directive {{myData.textf()}}
will be called on the model object myData.textf()
function $scope
and inserts the text returned from the function into the HTML template.
The textf()
function is inserted into the $scope.myData
object inside the controller function, as you can see in the example.
##ng-bind directive
Theng-bind directive is a replacement for the interpolation directive. You can use it by
ng-bind inserting an attribute in the HTML element where you want AngularJS to insert data. Here's an example:
<div ng-controller="MyController" > <span ng-bind="myData.textf()"></span> </div>
myData.text() function into the body of the
span element. Please note that the
ng-bind surrounding the expression within the attribute
{{ }} is not required.