Controller and Scope
Controller
Create and use controllers
angular.module("exampleApp", []) .controller("simpleCtrl", function ($scope) { $scope.setAddress = function (type, zip) { $scope[type] = zip; } $scope.copyAddress = function () { $scope.shippingZip = $scope.billingZip; } })
Controllers are created using the controller method provided by the Module object of AngularJS.The parameter to the controller method is the name of the new controller and a function that will be used to create the controller.This function can use the dependency injection feature to declare dependency on the Angular JS service.For example, $scope is used by almost every controller.
<div ng-controller="simpleCtrl"> <h4>Billing Zip Code: {{billingZip}}</h4> <div> <input ng-model="zip" /> </div> <button ng-click="setAddress('billingZip', zip)">Save Billing</button> </div>
Ng-controllers are used to specify the scope of the controller and controller used (the scope of the command and all the labels it contains)
Scope
The most important thing about scopes is that modifications propagate, automatically updating all dependent data values, even through behavior.
Reuse the same controller
We can create multiple views in the same application and use the same controller.Angular JS will call each factory function applied to the controller (the function used to create the controller), and each controller instance will have its own scope.
That is, even if both views use the same controller.As long as the scope of the controllers does not overlap, a variable in one controller is not associated with another controller with the same name.It can be simply understood as two people with the same name.
<!DOCTYPE html> <html ng-app="exampleApp"> <head> <title>AngularJS Demo</title> <meta charset="utf-8"/> <script type="text/javascript" src="angular-1.5.8/angular.min.js"></script> </head> <body> <div ng-controller="simpleCtrl"> <h4>Billing Zip Code: {{billingZip}}</h4> <div> <input ng-model="zip" /> </div> <button ng-click="setAddress('billingZip', zip)">Save Billing</button> </div> <div ng-controller="simpleCtrl"> <h4>Shilling Zip Code: {{shippingZip}}</h4> <div> <input ng-model="zip" /> </div> <button ng-click="copyAddress()">Use Billing</button> <button ng-click="setAddress('shippingZip', zip)">Save Shipping</button> </div> </body> <script type="text/javascript"> angular.module("exampleApp", []) .controller("simpleCtrl", function ($scope) { $scope.setAddress = function (type, zip) { $scope[type] = zip; } $scope.copyAddress = function () { $scope.shippingZip = $scope.billingZip; } }) </script> </html>
In the above code, after setting billingZip in the first controller, the Use Billing button in the second controller will still set a null value for shippingZip because billingZip in the first controller will not affect the second controller.