AngularJS核心语法与指令详解

作者:百宝袋

时间:2026-10-28

浏览:433

本文详细解析AngularJS的核心语法,涵盖从模板加载到DOM渲染的完整流程。重点讲解文本显示的双花括号与ng-bind区别、表单输入中的ng-model与事件监听、列表迭代的ng-repeat用法,以及通过ng-show、ng-class实现的条件显示与动态样式控制,帮助开发者掌握AngularJS的基础视图构建能力。

文章目录

AngularJS模板与数据绑定流程

模板与数据的交互遵循特定的生命周期。

当用户访问应用首页时,浏览器向服务器发起HTTP请求并加载index.html。该页面引入了Angular框架,框架在DOM加载完成后扫描ng-app指令以界定应用范围。随后,Angular解析模板中的绑定关系,执行DOM操作、注册监听器并获取初始化数据,最终将模板转换为可视化的DOM视图。应用启动后,可进一步从服务器加载其他动态数据。

文本显示与表单交互

文本显示

AngularJS提供两种文本渲染方式:一是使用双大括号语法{{greeting}},二是通过ng-bind指令绑定属性ng-bind="greeting"。

使用双大括号语法时,若页面加载缓慢,用户可能短暂看到未渲染的原始表达式。因此,建议在index.html等首屏页面优先使用ng-bind指令,其他页面可根据需求选择双大括号语法。

表单输入

代码如下:

<html ng-app>
<head>
<title>表单</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
function StartUpController($scope) {
$scope.funding = {startingEstimate:0};
computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
        };
$scope.$watch('funding.startingEstimate',computeNeeded); //watch model的变化
    }
</script>
</head>
<body>
<form ng-controller="StartUpController">
Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate"> //change的时候调用函数
Recommendation: {{funding.needed}}
</form>
</body>
</html>

在某些场景下,无需对每次输入变化立即响应,而是需要延迟处理。例如:

代码如下:

<html ng-app>
<head>
<title>表单</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
function StartUpController($scope) {
$scope.funding = {startingEstimate:0};
computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
        };
$scope.$watch('funding.startingEstimate',computeNeeded);//watch监视一个表达式,当这个表达式发生变化时就会调用一个回调函数
$scope.requestFunding = function() {
window.alert("Sorry,please get more customers first.")
        };
    }
</script>
</head>
<body>
<form ng-submit="requestFunding()" ng-controller="StartUpController"> //ng-submit
Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">
Recommendation: {{funding.needed}}
<button>Fund my startup!</button>
</form>
</body>
</html>

对于非表单提交的交互,如按钮点击,可以使用ng-click指令。

代码如下:

<html ng-app>
<head>
<title>表单</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
function StartUpController($scope) {
$scope.funding = {startingEstimate:0};
computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
        };
$scope.$watch('funding.startingEstimate',computeNeeded);
$scope.requestFunding = function() {
window.alert("Sorry,please get more customers first.")
        };
$scope.reset = function() {
$scope.funding.startingEstimate = 0;
        };
    }
</script>
</head>
<body>
<form ng-controller="StartUpController">
Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">
Recommendation: {{funding.needed}}
<button ng-click="requestFunding()">Fund my startup!</button>
<button ng-click="reset()">Reset</button>
</form>
</body>
</html>

列表迭代与视图控制

列表、表格以及其他迭代型元素

ng-repeat指令用于遍历集合,并通过$index变量返回当前元素的索引。示例代码如下:

代码如下:

<html ng-app>
<head>
<title>表单</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
var students = [{name:'Mary',score:10},{name:'Jerry',score:20},{name:'Jack',score:30}]
function StudentListController($scope) {
$scope.students = students;
}
 </script>
</head>
<body>
 <table ng-controller="StudentListController">
 <tr ng-repeat='student in students'>
 <td>{{$index+1}}</td>
 <td>{{student.name}}</td>
 <td>{{student.score}}</td>
 </tr>
 </table>
</body>
</html>

隐藏与显示 ng-show和ng-hide功能互补,分别用于控制元素的显示与隐藏状态。

代码如下:

<html ng-app>
<head>
<script type="text/javascript" src="angular.min.js"></script>
<script>
function DeathrayMenuController($scope) {
$scope.menuState = {show:false };//这里换成menuState.show = false 效果就显示不出来了。以后声明变量还是放在{}里面吧
$scope.toggleMenu = function() {
$scope.menuState.show = !$scope.menuState.show;
    };
  }
</script>
</head>
<body>
<div ng-controller='DeathrayMenuController'>
<button ng-click='toggleMenu()'>Toggle Menu</button>
<ul ng-show='menuState.show'>
<li ng-click='stun()'>Stun</li>
<li ng-click='disintegrate()'>Disintegrate</li>
<li ng-click='erase()'>Erase from history</li>
</ul>
</div>
</body>
</html>

css类和样式

ng-class和ng-style指令均接受表达式,其返回值可以是:

以空格分隔的CSS类名字符串 css类名数组 css类名到布尔值的映射对象 代码示例如下:

代码如下:

<html ng-app>
<head>
<style type="text/css">
.error {
background-color: red;
    }
.warning {
background-color: yellow;
    }
</style>
<script type="text/javascript" src="angular.min.js"></script>
<script>
function HeaderController($scope) {
$scope.isError = false;
$scope.isWarning = false;
$scope.showError = function() {
 $scope.messageText = "Error!!!!"
 $scope.isError = true;
 $scope.isWarning = false;
 }
$scope.showWarning = function() {
 $scope.messageText = "Warning!!!"
 $scope.isWarning = true;
 $scope.isError = true;
 }
 }
</script>
</head>
<body>
<div ng-controller="HeaderController">
<div ng-class="{error:isError,warning:warning}">{{messageText}}</div>
 <button ng-click="showError()">Error</button>
 <button ng-click="showWarning()">Warning</button>
</div>
</body>
</html>

css类名到布尔值的映射 示例代码如下:

代码如下:

<html ng-app>
<head>
<style type="text/css">
.selected {
background-color: lightgreen;
    }
</style>
<script type="text/javascript" src="angular.min.js"></script>
<script>
function Restaurant($scope) {
$scope.list = [{name:"The Handsome",cuisine:"BBQ"},{name:"Green",cuisine:"Salads"},{name:"House",cuisine:'Seafood'}];
$scope.selectRestaurant = function(row) {
 $scope.selectedRow = row;
 }
 }
</script>
</head>
<body>
<table ng-controller="Restaurant">
 <tr ng-repeat='restaurant in list' ng-click='selectRestaurant($index)' ng-class='{selected: $index==selectedRow}'> //css类名到布尔值的映射,当模型属性selectedRow的值等于ng-repeat中得$index时,selectd样式就会被设置到那一行
 <td>{{restaurant.name}}</td>
 <td>{{restaurant.cuisine}}</td>
 </tr>
</table>
</body>
</html>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章