2013-10-15 51 views
2

我想將Angular模型綁定到Knockout組件。它正在工作 - 當Angular模型更改Knockout綁定時適用。但問題的方向相反 - 我希望Angular模型在Knockout組件更改時進行更新,並且在不觸及組件的情況下(它不必知道Angular包裝器)。 目標 - 使用Angular在KO組件周圍構建一個快速原型框架,該組件正在其他環境中使用。 KO組件可以並應該共享模型(來自Angular wrapper),因此這個問題。Angular - Knockout模型共享

編輯: 這是一個jsFiddle示例來展示我想要達到的目標。 它是一種簡化,因爲在現實世界中,KO組件將使用內部虛擬機,這將難以收看。但即使在這裏,我也不明白爲什麼$ watch不起作用。

var sharedData = { 
    personName: "alex", 
    personAge: "32" 
}; 


function WrapperCtrl($scope){ 
    $.each(sharedData, function(key, value) { 
     sharedData[key] = (typeof value !== "function") ? ko.observable(value) : value; 
    }); 

    $scope.wrapData = sharedData; 

    ko.applyBindings(sharedData, document.getElementById("ko_1")); 
    ko.applyBindings(sharedData, document.getElementById("ko_2")); 

    $scope.$watch(
     function() { 
      return sharedData.personName(); 
     }, 
     function(newValue, oldValue) { 
      console.log("change"); 
     } 
    ); 

    $scope.doSomething = function(){ 
     console.log("before angular function: ", $scope.wrapData.personName(), $scope.wrapData.personAge()) 
     sharedData.personName('Bob').personAge(41); 
     console.log("after angular function: ", $scope.wrapData.personName(), $scope.wrapData.personAge()) 
    }; 
} 


function doSomething() { 

    console.log("before knockout function", sharedData.personName(), sharedData.personAge()) 
    sharedData.personName('Mary').personAge(25); 
    console.log("after knockout function", sharedData.personName(), sharedData.personAge()) 
} 
+0

請做出的jsfiddle例子或張貼一張你的代碼。 – frkk

+0

這裏是小提琴:http://jsfiddle.net/HmcnB/10/ – krulik

回答

0

如果你不允許直接插入角度綁定到你的組件,那麼你將不能夠火過你的消化週期等角度會不知道你的數據源已更新。解決這個的方法之一是定期調用$申請,這將與任何外部的變化,這樣的更新模式:

setInterval($scope.$apply, 500); 

http://jsfiddle.net/HmcnB/11/

+0

變量的範圍是什麼?我如何才能觀察KO組件內的數據? – krulik

+0

請參閱附件提琴:http://jsfiddle.net/HmcnB/10/ – krulik

+0

對不起,我的錯誤 - 因爲你的淘汰賽組件必須完全獨立於你的角度 - 沒有辦法讓角度知道它需要執行消化週期,所以它不會激發你的觀察者。處理這個問題的一個(稍微粗糙的)方法是調用一個週期性的$ apply,它將用更改來更新您的範圍模型。 http://jsfiddle.net/HmcnB/11/ –