AngularJs控制器控制应用程序(的数据).
AngularJs控制器是常规的JavaScript对象,由标准的JavaScript对象的构造函数创建
ng-controller指令定义了应用程序控制器.
<div ng-app="myApp" ng-controller="myCtrl"> <label for="">名:<input type="text" ng-model="firstName"></label> <label for="">姓:<input type="text" ng-model="lastName"></label> <br /> 姓名:{{firstName + lastName}} </div> <script> var app = angular.module("myApp",[]); app.controller("myCtrl",function($scope){ $scope.firstName = "hehe"; $scope.lastName = "老街"; }) </script>
应用解析:
AngularJs应用程序由ng-app定义,应用程序在<div>内运行。
ng-controller="myCtrl"属性是一个AngularJS的一个指令,用来定义一个控制器。
AngularJS使用$scope对象来调用控制器。
在AngularJs中,$scope是一个应用对象(属于应用变量和函数).
控制器的$scope(相当于作用域、控制范围)用来保存AngularJs Model(模型)
控制器在作用域中创建了两个属性(firstName和lastName)
ng-model指令绑定输入域到控制器的属性(firstName和lastName).
控制器方法:
<div ng-app="myApp" ng-controller="myCtrl"> <label for="">名:<input type="text" ng-model="firstName"></label> <label for="">姓:<input type="text" ng-model="lastName"></label> <br /> 姓名:{{fullName()} </div> <script> var app = angular.module("myApp",[]); app.controller("myCtrl",function($scope){ $scope.firstName = "hehe"; $scope.lastName = "老街"; $scope.fullName = function () { return $scope.firstName + "" + $scope.lastName; } }) </script>
外部文件中的控制器
<div ng-app="myApp" ng-controller="namesCtrl"> <ul> <li ng-repeat="x in names"> {{x.name + "," +x.country}} </li> </ul> </div> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script src="namesController.js"></script>
angular.module("myApp",[]).controller("namesCtrl",function($scope){ $scope.names = [ {name:"Jani",country:"Norway"}, {name:"Hege",country:"Sweden"}, {name:"Kai",country:"Denmark"} ]; })