我正在尝试在两个独立控制器和一个共享服务(提供另一个隔离范围)之间创建双向数据绑定:
app.factory("sharedScope", function($rootScope) {
var scope = $rootScope.$new(true);
scope.data = "init text from factory";
return scope;
});
app.controller("first", function($scope, sharedScope) {
$scope.data1 = sharedScope.data;
});
app.controller("second", function($scope, sharedScope) {
$scope.data2 = sharedScope.data;
});
小提琴:http://jsfiddle.net/akashivskyy/MLuJA/
当应用程序启动时,data1
和data2
已正确更新为init text from factory
,但稍后,如果我更改其中任何一项,则这些更改不会反映在这三个范围内。
如何绑定它们?
P.S。如果有一个更好的方法,而不是返回一个范围,仍然可以访问事件和观察功能(基本上不重写它们),请告诉我。 :)
答案 0 :(得分:18)
修正了它。如果你使用原语,就会丢失参考文献,就像你的小提琴一样。
检查一下:
app.factory("sharedScope", function($rootScope) {
var scope = $rootScope.$new(true);
scope.data = {text: "init text from factory"};
return scope;
});
app.controller("first", function($scope, sharedScope) {
$scope.data1 = sharedScope.data;
});
app.controller("second", function($scope, sharedScope) {
$scope.data2 = sharedScope.data;
});
答案 1 :(得分:6)
又一个有趣的一点:在这种情况下,您不需要注入$ scope或$ rootScope。如果您使用Controller As,以下代码可以正常工作。 查看Fiddle
var app = angular.module("app", []);
app.factory("sharedScope", function() {
var _this = this;
_this.data = {text: "init text from factory"};
return _this;
});
app.controller("first", function(sharedScope) {
var _this = this;
_this.data1 = sharedScope.data;
});
app.controller("second", function(sharedScope) {
var _this = this;
_this.data2 = sharedScope.data;
});
为了获得更多乐趣,请将控制器,服务和工厂视为类。 More Fiddles
var app = angular.module("app", []);
var SharedScope = function(){
var _this = this;
_this.data = {text: "init text from factory"};
return _this;
};
app.factory("sharedScope", SharedScope);
var First = function(sharedScope){
var _this = this;
_this.data1 = sharedScope.data;
};
var Second = function(sharedScope){
var _this = this;
_this.data2 = sharedScope.data;
};
First.$inject = ['sharedScope'];
Second.$inject = ['sharedScope'];
app.controller("first", First);
app.controller("second", Second);
我一直在扮演Josh Carroll的Guidelines to Avoid "Scope Soup"
答案 2 :(得分:4)
JavaScript通过引用传递对象,因此所有范围都将指向同一个对象。为什么不这样做?
app.factory("sharedData", function() {
return {data: "init text from factory"};
});
app.controller("first", function($scope, sharedData) {
$scope.sharedData = sharedData;
});
app.controller("second", function($scope, sharedData) {
$scope.sharedData = sharedData;
});
并在您看来:
<p>{{sharedData.data}}</p>