[英]AngularJS : How to create a two-way data binding between two isolated controllers and a shared service?
我試圖在兩個隔離的控制器和一個共享服務(提供另一個隔離的范圍)之間創建雙向數據綁定:
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
正確更新為init text from factory
,但稍后,如果我更改其中任何一個,那么這些更改不會反映在這三個范圍中。
我該如何綁定它們?
PS如果有一個更好的方法,而不是返回一個范圍,仍然可以訪問事件和觀察功能(基本上不重寫它們),請告訴我。 :)
固定它。 如果你使用原語,就會丟失引用,就像你的小提琴一樣。
檢查一下:
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;
});
還有一點有趣的是:在這種情況下,您不需要注入$ 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;
});
為了獲得更多樂趣,請將控制器,服務和工廠視為類。 更多小提琴
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的避免“范圍湯”指南
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.