您的位置:首页 > Web前端 > AngularJS

JS 前端框架6 AngularJS 入门使用

2015-07-03 15:46 676 查看

简介

AngularJS 是一款前端框架,主要考虑的是CRUD应用,采用模板的语法。

官网地址:

https://angularjs.org/

github:

https://github.com/angular/angular.js

入门示例

第一个html示例:

<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>


绑定html代码

ng-bind-html-unsafe


angularjs 的双向绑定

<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
</head>
<body>
Your name: <input type="text" ng-model="yourname" placeholder="World">
<hr>
Hello {{yourname || 'World'}}!
</body>
</html>


这里模型变量的一个方向修改,会自动反映到另一个变量上去。

控制器

<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">

<ul>
<li ng-repeat="phone in phones">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</body>
</html>


function PhoneListCtrl($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster with Nexus S."},
{"name": "Motorola XOOM™ with Wi-Fi",
"snippet": "The Next, Next Generation tablet."},
{"name": "MOTOROLA XOOM™",
"snippet": "The Next, Next Generation tablet."}
];
}


迭代器&过滤

<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>


迭代里使用$index取得当前下标。

ajax示例

get示例

$http({
url: url,
method: 'GET',
cache: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': localStorage.authorization
},
params: {
page: 1,
rows: 50
}
}).success(function (list) {
console.info('result', list);
}).error(function (e) {
console.error('加载机型错误', e);
callback(null);
});


post示例

$http({
'url': url,
'method': 'post',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': localStorage.authorization
},
transformRequest: transformRequest
}).then(function (response, status, headers, config) {
console.log(response, status, headers, config);
}, function () {
//
});
function transformRequest(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}


Tips

序列化

angular.fromJson(data);


浅拷贝与深拷贝

angular.copy(source,destination);
angular.extend({},source); 返回拷贝后对象


ng-class

ng-class="{true:'gray',false:''}[$root.offline]"
//使用的属性是定义在$rootScope里时,要使用$root.
//定义在$scope里时,是不需要前缀的


本文内容来源:

http://angularjs.apjs.net/

https://angularjs.org/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: