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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。