AngularJS中的ng-controller指令用于向应用程序添加控制器。它可以用来添加可以在某些事件(例如click等)上调用的方法,函数和变量,以执行某些操作。
用法:
<element ng-controller="expression"> Contents... </element>
其中,表达式是指控制器的名称。
范例1:本示例使用ng-controller指令显示输入元素。
<!DOCTYPE html>
<html>
<head>
<title>ng-controller Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
</head>
<body ng-app="app" style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h2>ng-controller Directive</h2><br>
<div ng-controller="geek">
Name:<input class="form-control" type="text"
ng-model="name">
<br><br>
You entered:<b><span>{{name}}</span></b>
</div>
<script>
var app = angular.module('app', []);
app.controller('geek', function ($scope) {
$scope.name = "geeksforgeeks";
});
</script>
</body>
</html>
输出:
范例2:本示例使用ng-controller指令在单击按钮后显示内容。
<!DOCTYPE html>
<html>
<head>
<title>ng-controller Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
</head>
<body ng-app="app" style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h2>ng-click Directive</h2>
<div ng-controller="app">
<button class="btn btn-default" ng-click="best()">
Button 1
</button>
<button class="btn btn-primary" ng-click="notbest()">
Button 2
</button><br>
<p>Quick sort is <b>{{res}}</b>.</p>
</div>
<script>
var app = angular.module('app', []);
app.controller('app', function ($scope) {
$scope.best = function () {
return $scope.res = "best";
};
$scope.notbest = function () {
return $scope.res = "not always good";
};
});
</script>
</body>
</html>
输出:
点击之前:
单击按钮2后:
相关用法
- AngularJS ng-if用法及代码示例
- AngularJS ng-cut用法及代码示例
- AngularJS ng-value用法及代码示例
- AngularJS ng-src用法及代码示例
- AngularJS ng-app用法及代码示例
- AngularJS ng-csp用法及代码示例
- AngularJS ng-jq用法及代码示例
- AngularJS ng-required用法及代码示例
- AngularJS ng-bind用法及代码示例
- AngularJS ng-srcset用法及代码示例
- AngularJS ng-paste用法及代码示例
- AngularJS ng-submit用法及代码示例
- AngularJS ng-style用法及代码示例
- AngularJS ng-selected用法及代码示例
注:本文由纯净天空筛选整理自Vishal Chaudhary 2大神的英文原创作品 AngularJS | ng-controller Directive。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。