aka*_*kyy 13 javascript angularjs angularjs-scope angularjs-controller
我试图在两个隔离的控制器和一个共享服务(提供另一个隔离的范围)之间创建双向数据绑定:
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;
});
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/akashivskyy/MLuJA/
当应用程序启动data1并data2正确更新时init text from factory,如果我更改了其中任何一个,那么这些更改不会反映在这三个范围中.
我该如何绑定它们?
PS如果有一个更好的方法,而不是返回一个范围,仍然可以访问事件和观察功能(基本上不重写它们),请告诉我.:)
lin*_*ink 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;
});
Run Code Online (Sandbox Code Playgroud)
还有一点有趣的是:在这种情况下,您不需要注入$ scope或$ rootScope.如果您使用Controller As,以下代码可以正常工作.检查小提琴
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;
});
Run Code Online (Sandbox Code Playgroud)
为了获得更多乐趣,请将控制器,服务和工厂视为类. 更多小提琴
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);
Run Code Online (Sandbox Code Playgroud)
我一直在玩Josh Carroll的避免"范围汤"指南
| 归档时间: |
|
| 查看次数: |
10030 次 |
| 最近记录: |