最好保持工厂更新的方法是不使用$ scope。 以下是使用共享服务在控制器之间共享数据但不使用$ scope的更高级解决方案。
HTML
<div ng-app="myApp">
<div ng-controller="Controller1 as ctrl">
</br>
<table>
<tr>
<td><B> Enter Age in Controller1</B></td>
<td><input type="text" ng-model="ctrl.userAge"></select></td>
<td><button ng-click="ctrl.userLoggedIn=true"/>Submit</td>
</tr>
</table>
</div>
<div ng-controller="Controller2 as ctrl">
<table>
<tr>
<td><B> Age in controller2 : </B></td>
<td>{{ctrl.userAge}}</td>
</tr>
<tr>
<td><B> LoggedIn in controller2 : </B></td>
<td>{{ctrl.userLoggedIn}}</td>
</tr>
</table>
</div>
</div>
JS
(function(app) {
function SharedService() {
this.user = {};
}
angular.extend(SharedService.prototype, {
getUser: function() {
return this.user;
},
setUser: function(user) {
this.user = user;
}
});
function Controller1(SharedService) {
this.sharedService = SharedService;
}
Object.defineProperty(Controller1.prototype,
'userAge', {
enumerable: true, //indicate that it supports enumerations
configurable: false, //disable delete operation
get: function() {
return this.sharedService.getUser().age;
},
set: function(val) {
this.sharedService.getUser().age=val;
}
});
Object.defineProperty(Controller1.prototype,
'userLoggedIn', {
enumerable: true, //indicate that it supports enumerations
configurable: false, //disable delete operation
get: function() {
return this.sharedService.getUser().loggedIn;
},
set: function(val) {
this.sharedService.getUser().loggedIn=val;
}
});
function Controller2(SharedService) {
this.sharedService = SharedService;
}
Object.defineProperty(Controller2.prototype,
'userAge', {
enumerable: true, //indicate that it supports enumerations
configurable: false, //disable delete operation
get: function() {
return this.sharedService.getUser().age;
},
set: function(val) {
this.sharedService.getUser().age=val;
}
});
Object.defineProperty(Controller2.prototype,
'userLoggedIn', {
enumerable: true, //indicate that it supports enumerations
configurable: false, //disable delete operation
get: function() {
return this.sharedService.getUser().loggedIn;
},
set: function(val) {
this.sharedService.getUser().loggedIn=val;
}
});
app.service('SharedService', SharedService);
app.controller('Controller1', Controller1);
app.controller('Controller2', Controller2);
})(angular.module('myApp', []));