
AngularJS 控制器控制AngularJS 應(yīng)用程序的數(shù)據(jù)。AngularJS 控制器是常規(guī)的JavaScript 對象。AngularJS 控制器AngularJS 應(yīng)用程序被控制器控制。ng-controller指令定義了應(yīng)用程序控制器??刂破魇荍avaScript 對象由標準的 JavaScript對象的構(gòu)造函數(shù)創(chuàng)建。AngularJS 實例div ng-appmyApp ng-controllermyCtrl名: input typetext ng-modelfirstNamebr姓: input typetext ng-modellastNamebrbr姓名: {{firstName lastName}}/divscriptvar app angular.module(myApp, []);app.controller(myCtrl, function($scope) {$scope.firstName John;$scope.lastName Doe;});/script嘗試一下 ?應(yīng)用解析AngularJS 應(yīng)用程序由ng-app定義。應(yīng)用程序在 div 內(nèi)運行。ng-controllermyCtrl屬性是一個 AngularJS 指令。用于定義一個控制器。myCtrl函數(shù)是一個 JavaScript 函數(shù)。AngularJS 使用$scope對象來調(diào)用控制器。在 AngularJS 中 $scope 是一個應(yīng)用對象(屬于應(yīng)用變量和函數(shù))??刂破鞯?scope相當于作用域、控制范圍用來保存AngularJS Model(模型)的對象??刂破髟谧饔糜蛑袆?chuàng)建了兩個屬性 (firstName和lastName)。ng-model指令綁定輸入域到控制器的屬性firstName 和 lastName。控制器方法上面的實例演示了一個帶有 lastName 和 firstName 這兩個屬性的控制器對象??刂破饕部梢杂蟹椒ㄗ兞亢秃瘮?shù)AngularJS 實例div ng-appmyApp ng-controllerpersonCtrl名: input typetext ng-modelfirstNamebr姓: input typetext ng-modellastNamebrbr姓名: {{fullName()}}/divscriptvar app angular.module(myApp, []);app.controller(personCtrl, function($scope) {$scope.firstName John;$scope.lastName Doe;$scope.fullName function() {return $scope.firstName $scope.lastName;}});/script嘗試一下 ?外部文件中的控制器在大型的應(yīng)用程序中通常是把控制器存儲在外部文件中。只需要把 script 標簽中的代碼復制到名為 personController.js 的外部文件中即可AngularJS 實例div ng-appmyApp ng-controllerpersonCtrlFirst Name: input typetext ng-modelfirstNamebrLast Name: input typetext ng-modellastNamebrbrFull Name: {{firstName lastName}}/divscript srcpersonController.js/script其他實例以下實例創(chuàng)建一個新的控制器文件:angular.module(myApp, []).controller(namesCtrl, function($scope) { $scope.names [ {name:Jani,country:Norway}, {name:Hege,country:Sweden}, {name:Kai,country:Denmark} ]; });保存文件為 namesController.js:然后在應(yīng)用中使用控制器文件:AngularJS 實例div ng-appmyApp ng-controllernamesCtrlulli ng-repeatx in names{{ x.name , x.country }}/li/ul/divscript srcnamesController.js/script