最近在学习angular.js,为此方便加深对angular.js前端框架的理解,因此写下这篇angular.js入门
首先介绍下什么是angular.js?
AngularJS 是一个 JavaScript 框架。它可通过 <script> 标签添加到 HTML 页面。
AngularJS 通过 指令 扩展了 HTML,且通过 表达式 绑定数据到 HTML。
好处:
AngularJS 使得开发现代的单一页面应用程序(SPAs:Single Page Applications)变得更加容易。
- AngularJS 把应用程序数据绑定到 HTML 元素。
- AngularJS 可以克隆和重复 HTML 元素。
- AngularJS 可以隐藏和显示 HTML 元素。
- AngularJS 可以在 HTML 元素"背后"添加代码。
- AngularJS 支持输入验证。
各个 angular.js 版本下载: https://github.com/angular/angular.js/releases
一、AngularJS表达式
AngularJS 表达式写在双大括号内:{{ expression }}。
AngularJS 表达式把数据绑定到 HTML,这与 ng-bind 指令有异曲同工之妙。
AngularJS 将在表达式书写的位置"输出"数据。
<div ng-app="" ng-init="quantity=1;cost=5"> <p>总价: {{ quantity * cost }}</p> </div> <div ng-app="" ng-init="firstName='John';lastName='Doe'"> <p>姓名: <span ng-bind="firstName + ' ' + lastName"></span></p> </div> <div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}"> <p>姓为 {{ person.lastName }}</p> </div>
二、AngularJS指令
<div ng-app="" ng-init="firstName='John'">
<p>在输入框中尝试输入:</p>
<p>姓名:<input type="text" ng-model="firstName"></p>
<p>你输入的为: {{ firstName }}</p>
</div>
<div ng-app="" ng-init="quantity=1;price=5">
<h2>价格计算器</h2>
数量: <input type="number" ng-model="quantity">
价格: <input type="number" ng-model="price">
<p><b>总价:</b> {{ quantity * price }}</p>
</div>
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<p>使用 ng-repeat 来循环数组</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<p>循环对象:</p>
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
angular.module('myApp',[]).directive('zl1',[ function(){
return {
restrict:'AE',
template:'thirective',
link:function($scope,elm,attr,controller){
console.log("这是link");
},
controller:function($scope,$element,$attrs){
console.log("这是con");
}
};
}]).controller('Con1',['$scope',function($scope){
$scope.name="aliceqqq";
}]);
三、AngularJS模型
<div ng-app="myApp" ng-controller="myCtrl"> 名字: <input ng-model="name"> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.name = "John Doe"; }); </script>