簡述AngularJS的控制器的使用
AngularJS應(yīng)用主要依賴于控制器來控制數(shù)據(jù)在應(yīng)用程序中的流動。控制器采用ng-controller指令定義。控制器是一個包含屬性/屬性和JavaScript對象的功能。每個控制器接受$scope參數(shù)指定應(yīng)用程序/模塊,由控制器控制。
<div ng-app="" ng-controller="studentController"> ... </div>
在這里,我們已經(jīng)聲明采用ng-controller指令的控制器studentController。作為下一步,我們將定義studentController如下
- studentController 定義 $scope 作為JavaScript對象參數(shù)。
- $scope 表示應(yīng)用程序,使用studentController對象。
- $scope.student 是studentController對象的屬性。
- firstName和lastName是$scope.student 對象的兩個屬性。我們已經(jīng)通過了默認(rèn)值給他們。
- fullName 是$scope.student對象的函數(shù),它的任務(wù)是返回合并的名稱。
- 在fullName函數(shù)中,我們現(xiàn)在要學(xué)生對象返回組合的名字。
- 作為一個說明,還可以定義控制器對象在單獨的JS文件,并把有關(guān)文件中的HTML頁面。
<script> function studentController($scope) { $scope.student = { firstName: "yiibai", lastName: "com", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script>
現(xiàn)在可以使用ng-model或使用表達式如下使用studentController學(xué)生的屬性。
- 現(xiàn)在有 student.firstName 和 student.lastname 兩個輸入框。
- 現(xiàn)在有 student.fullName()方法添加到HTML。
- 現(xiàn)在,只要輸入first name和lastname輸入框中輸入什么,可以看到兩個名稱自動更新。
Enter first name: <input type="text" ng-model="student.firstName"><br> Enter last name: <input type="text" ng-model="student.lastName"><br> <br> You are entering: {{student.fullName()}}
例子
下面的例子將展示使用控制器。
testAngularJS.html 文件內(nèi)容如下:
<html> <head> <title>Angular JS Controller</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" ng-controller="studentController"> Enter first name: <input type="text" ng-model="student.firstName"><br><br> Enter last name: <input type="text" ng-model="student.lastName"><br> <br> You are entering: {{student.fullName()}} </div> <script> function studentController($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
輸出
在Web瀏覽器打開textAngularJS.html,看到以下結(jié)果:
相關(guān)文章
AngularJS通過ng-Img-Crop實現(xiàn)頭像截取的示例
本篇文章主要介紹了AngularJS通過ng-Img-Crop實現(xiàn)頭像截取的示例,具有一定的參考價值,有興趣的可以了解一下2017-08-08Angular發(fā)布1.5正式版,專注于向Angular 2的過渡
Angular團隊最近發(fā)布了Angular 1.5的正式版,該版本實現(xiàn)了一次重大的升級,它讓仍在使用1.X版本的開發(fā)者將能夠更容易地過渡到Angular 2的開發(fā)2016-02-02AngularJS使用帶屬性值的ng-app指令實現(xiàn)自定義模塊自動加載的方法
這篇文章主要介紹了AngularJS使用帶屬性值的ng-app指令實現(xiàn)自定義模塊自動加載的方法,結(jié)合實例形式分析了ng-app自動加載我們自定義的模塊作為根模塊的操作步驟與實現(xiàn)技巧,需要的朋友可以參考下2017-01-01Angular.js與Bootstrap相結(jié)合實現(xiàn)表格分頁代碼
最近一直在學(xué)習(xí)angularjs相關(guān)知識,在學(xué)習(xí)過程中寫了一個小demo,下面把代碼思路分享給大家,感興趣的朋友一起學(xué)習(xí)2016-04-04ionic+AngularJs實現(xiàn)獲取驗證碼倒計時按鈕
本篇文章主要介紹了ionic+AngularJs實現(xiàn)獲取驗證碼倒計時按鈕,具有一定的參考價值,有興趣的可以了解一下。2017-04-04