[Angular] Parent scope, scope overwritten, using factory() to share data between controller
binding: 通常可以使用ng-model来做绑定!
Scope作用域:
<!DOCTYPE html> <html> <head> <title>Angular Binding</title> <script src="main.js"></script> <!--<link rel="stylesheet" href="css.css" />--> </head> <body> <div ng-app=""> <input type="text" ng-model="data.message" /> <h1>{{data.message}}</h1> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> <h1>{{data.message}}</h1> </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="data.message" /> <h1>{{data.message}}</h1> </div> </div> <script src="angular.min.js"></script> </body> </html>
function FirstCtrl($scope){ } function SecondCtrl($scope){ }
When you type in first input, the FirstCtrl and SecondCtrl will get update also>>>
This is because those three are all inside <div ng-app=""></div> this scope has
<input type="text" ng-model="data.message" /> <h1>{{data.message}}</h1>
In other words, <div ng-app=""></div> this scope is the parent scope of the FirstCtrl and SecondCtrl.
{{data.message}}
data.message's dot is important, it keeps parent's scope to all his children!. If remove 'data.', then child scope will override the parent scope!.
----------------------Sharing Data between controllere--------------------------------------------
If we remove:
<input type="text" ng-model="data.message" /> <h1>{{data.message}}</h1>
So FirstCtrl and SecondCtrl are no longer communicate, data will not sharing between those two.
We still can make two controller binded together by Javascript functions. It is will services:
https://docs.angularjs.org/guide/services
<!DOCTYPE html> <html> <head> <title>Angular Binding</title> <script src="angular.min.js"></script> <script src="main.js"></script> <!--<link rel="stylesheet" href="css.css" />--> </head> <body> <div ng-app="myApp"> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> <h1>{{data.message}}</h1> </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="data.message" /> <h1>{{data.message}}</h1> </div> </div> </body> </html>
var app = angular.module('myApp', []); app.factory('Data', function(){ return {message: "This is from service"} }) function FirstCtrl($scope, Data){ $scope.data = Data; } function SecondCtrl($scope,Data){ $scope.data = Data; }
Data is an Object: {message: This is from service};
Using factory to inject Data to Controller, then assign the Data to controller's scope.