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

angular.js初探

2015-07-27 22:51 766 查看
2015年7月27日 22:26:35 星期一

用在我论坛里的小栗子: 先列出来一级回帖, 点击帖子前边的"查看回复"按钮无刷新的去请求该帖子的所有回复

首先要引用js文件, 我这里使用的是bootstrap提供的cdn

<script src="http://cdn.bootcss.com/angular.js/1.4.3/angular.js"></script>


接下来是自己的js代码

//bbsController
bbsApp = angular.module('bbsApp',[]);
// bbsApp.controller('bbslist',['$scope',function($scope) {
//     $scope.answers= getBBSData();
//     $scope.bbsUrl = getBBSUrl();
//     //事件
//     $scope.showReplay = function(index) {
//         var id = $scope.answers[index].id;
//         var url = $scope.bbsUrl+'newbbsreplay?fid='+id;
//         $http.get(url).success(function(jsonReplay){
//             var replayData = 'replay_'+id;
//             $scope.replayData = jsonReplay;
//         });
//     }

// }]);

bbsApp.controller('bbslist',function($scope, $http) {
$scope.answers= getBBSData();
$scope.bbsUrl = getBBSUrl();
//点击事件
$scope.showReplay = function(index) {
var id = $scope.answers[index].id;
var url = $scope.bbsUrl+'newbbsreplay?fid='+id;
$http.get(url).success(function(jsonReplay){
for (i in jsonReplay) {
var intent = '';
for (var j = 0; j< jsonReplay[i].level; j++) {
intent += '|-';
}
jsonReplay[i].intent = intent;
}
$scope.answers[index].replays = jsonReplay;
});
}
});


这里第2行创建一个module, 就是创建一个angular BOOS级的功能模块

第3行和第18行是给这个模块绑定一个处理函数, 函数名字叫 'bbslist', 函数体是一个匿名函数

上边第3行到第16行, 也是可以用的, 只是这种方式, 匿名函数只能接收一个$scope参数,

对比一下18行, 这个方法可以传递多个内置参数, 第18行传递了两个参数, $scope, $http

接下来是html代码:

<!DOCTYPE html>
<html ng-app="bbsApp">
<head>
<meta charset="utf-8">
<script src="http://cdn.bootcss.com/angular.js/1.4.3/angular.js"></script>
<script src="<?= $baseUrl ?>bbs/js/bbs.js"></script>
</head>
<body ng-controller="bbslist">
<div ng-repeat="answer in answers">
<button ng-click="showReplay($index)">查看回复</button>
{{answer.id}} => {{answer.nickname}} => {{answer.content}}
<div ng-repeat="replay in answer.replays">
{{replay.intent}}{{replay.id}} => {{replay.nickname}} => {{replay.content}}
</div>
</div>
</body>
<script type="text/javascript">
function getBBSData ()
{
var jsonBBS = <?= $r ?>;
return jsonBBS;
}

function getBBSUrl()
{
return "<?= $controllerUrl ?>";
}
</script>
</html>


第2行, ng-app="bbsApp", 就是上边js代码里定义的那个BOOS级的功能的名字

第8行, ng-controller="bbslist", 就是控制器函数啦, 注意, 名字命名, 后边不必写后缀

第9行, ng-repeat, 就是循环(注意循环时, 包括ng-repeat所在的标签), 数据是内置变量$scope里的数据, 我在第20行, 通过PHP给一个变量赋值, 然后再js文件中获取再赋给$scope

第10行, ng-click, 就是点击事件, 那个$index就是ng-repeat时的索引(或下标)

第12行, 又是一个ng-repeat, 他是一个嵌套循环, 显示帖子的回复, 神奇就在这里, 我先写好了repeat程序, 但是并没有数据,

在ng-click绑定的点击事件发生后, (上边js代码22行开始)我动态把数据添加到$scope里, 然后html里的那个repeat程序, 自动就repeat显示了

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