Angular scope object and controller object
Based on AngularJS v1.2.29
Scope object
- It is a js instance object, and the ng app instruction creates a root scope object ($rootScope) by default
- Its properties and methods are associated with instructions or expressions on the page
Controller object
Is a js instance object used to control the application data of AngularJS
ng-controller
- Specifies the constructor of the controller, according to which AngularJS creates the controller object
- AngularJS creates a scope object $scope at the same time as the controller object, which is a child of $rootScope
- The constructor of the controller must have a parameter named $scope, and AngularJS will automatically pass in the $scope object
Raise a chestnut.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body ng-app> <div ng-controller="MyController"> <input type="text" ng-model="firstName"> <input type="text" ng-model="lastName"> <p>username1: {{firstName + '-' + lastName}}</p> <p>username2: {{getName()}}</p> </div> <script type="text/javascript" src="../../js/angular-1.2.29/angular.js"></script> <script type="text/javascript"> function MyController($scope) { console.log(this); console.log($scope); $scope.firstName = 'M'; $scope.lastName = 'xc'; $scope.getName = function () { console.log(this === $scope); return $scope.firstName + ' ' + this.lastName; } } </script> </body> </html>
Based on AngularJS v1.5.5
In the v1.5.5 version of angularjs, the theory of scope object and controller object has not changed a lot, but the usage has changed. For example, a chestnut.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <!-- Be careful: 1. ng-app Property value of instruction 2. Use Angular The module must be created first, then the controller must be created from the module --> <body ng-app="myApp"> <div ng-controller="c1"> <input type="text" ng-model="name"> <p>name: {{name}}</p> </div> <div ng-controller="c2"> <input type="text" ng-model="name"> <p>name: {{name}}</p> </div> <script type="text/javascript" src="../../js/angular-1.5.5/angular.js"></script> <script type="text/javascript"> /*var myAppModule = angular.module('myApp', []); myAppModule.controller('c1', function ($scope) { $scope.name = 'A'; }); myAppModule.controller('c2', function ($scope) { $scope.name = 'B'; });*/ // Chain call of Angular angular.module('myApp', []) .controller('c1', ['$scope', function ($scope) { $scope.name = 'A'; }]) .controller('c2', ['$scope', function ($scope) { $scope.name = 'B'; }]); </script> </body> </html>